0

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')

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

This doesn't work

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

I just get

[[None], [None], [None]]
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
rafello
  • 128
  • 2
  • 12

2 Answers2

5

Instead of using insert you could simply add the lists:

ls = [['x'] + i for i in ls]
[['x', 1, 2, 3], ['x', 4, 5, 6], ['x', 7, 8, 9]]

as noted, insert alters the list in-place returning None; that's what you populate the list you're creating with.

In Python >= 3.5 this can be prettified by unpacking in a list literal:

ls = [['x', *i] for i in ls]
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
3

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]
print(ls)
>> [['x', 1, 2, 3], ['x', 4, 5, 6], ['x', 7, 8, 9]]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • That's great, thanks for the explanation. There was a fundamental gap in my understanding of insert. – rafello Sep 29 '16 at 12:57