rafello rafello - 6 months ago 27
Python Question

List comprehension to add item to every list in a list of lists

I have a list of lists, and I want to add the same item to every list within the list of lists. I can do this with a for loop, but I'd like to know how to do it with a list comprehension.

ls = [[1,2,3],[4,5,6],[7,8,9]]

for i in ls:
i.insert(0, 'x')


This doesn't work

ls = [[i.insert(0, 'x')] for i in ls]

I just get

[[None], [None], [None]]


Because insert is inplace (it modifies the list it is called upon and returns None).

You could do [[i.insert(0, 'x')] for i in ls] (without re-assigning it to ls) but the explicit loop has better readability and no "magic" side effects.

ls = [[1,2,3],[4,5,6],[7,8,9]]
[[i.insert(0, 'x')] for i in ls]
>> [['x', 1, 2, 3], ['x', 4, 5, 6], ['x', 7, 8, 9]]