I understand that in-place list methods return None
instead of the mutated list. As far as I can see, this makes it impossible to use these methods as part of the internal logic of a list comprehension.
What is the most pythonic way to create a list comprehension whose members result from mutating other lists? In other words: what is the best alternative to this (non-functioning) line:
new_list = [old_list.insert(0, "X") for old_list in list_of_old_lists]
Which results in a list of None
s because list.insert()
returns None
.
Is it simply not possible to do this in an elegant single-line of code without a lot of slicing and concatenating?
The example above is trivial for the sake of illustrating my question but in reality I'd like to do this in more complex situations in lieu of multiple nested 'for' loops.
Here's a simplified sample of what I'm trying to do:
word = 'abcdefg'
variations_list = []
characters_to_insert = ['X', 'Y', 'Z']
for character in characters_to_insert:
for position in range(len(word) + 1):
w = list(word)
w.insert(position, character)
this_variation = ''.join(w)
variations_list.append(this_variation)
for v in variations_list:
print(v)
This works fine using nested 'for' loops, like this (my real application is much more complex/verbose than this sample).
But I cannot do the same thing using list comprehension because the 'insert' method returns None
:
variations_list_comprehension = [list(word).insert(position, character) for position in range(len(word) +1) for character in ['X', 'Y', 'Z']]
for v in variations_list_comprehension:
print(v)
Results in a list of None
values because the in-place mutations return "None".