I have a nested list that looks like this:
mylist = [['A;B', 'C'], ['D;E', 'F']]
I’d like to have it in the following form:
[['A', 'B', 'C'], ['D', 'E', 'F']]
Figured I’d write a simple list comprehension to do the task:
>>> newlist = [item[0].split(';').append(item[1]) for item in mylist]
>>> newlist
[None, None]
After some experimenting, I found that the error was in trying to use append() on anonymous lists:
>>> type(['A', 'B'])
<class 'list'>
>>> type(['A', 'B'].append('C'))
<class 'NoneType'>
Which seems like a gotcha, considering that you can do things like this:
>>> 'abc'.upper()
'ABC'
Obviously in most cases you could get around this by binding ['A', 'B'] to a variable before calling append(), but how would I make this work inside of a list comprehension? Furthermore, can anyone explain this unintuitive behavior?
As you found out, mutating methods aren’t of much use inside a list comprehension because the transient objects disappear immediately.
What works instead is to build-up a list through concatenation: