vemvir01
vemvir01

Reputation: 25

Using list comprehension to create list and extend in one line

I know there are many similarly titled questions but none of them answer my question which is why I cannot use a list comprehension to create a list and extend it with another list comprehension in the same line.

I want to try use:

['w' for i in range(7)].extend(['b' for i in range(6)])

to generate:

['w', 'w', 'w', 'w', 'w', 'w', 'w', 'b', 'b', 'b', 'b', 'b', 'b']

but end up with a NoneType object. I know I could simply use ['w' for i in range(7)] + ['b' for i in range(6)] or use (in two lines):

x = ['w' for i in range(7)]
x.extend(['b' for i in range(6)])

but I was just curious as to why I couldn't use the extend method on the list created using list comprehension with another list created using list comprehension in the same line.

Thanks.

Upvotes: 1

Views: 343

Answers (2)

Alderven
Alderven

Reputation: 8270

Actually you can do it one-line without extend:

['w' if i < 7 else 'b' for i in range(13)]

Output:

['w', 'w', 'w', 'w', 'w', 'w', 'w', 'b', 'b', 'b', 'b', 'b', 'b']

Upvotes: 0

Chris Curvey
Chris Curvey

Reputation: 10389

The why is because extend() operates on the underlying list and returns None. (It does NOT return the extended lsit.)

To illustrate, let's get rid of list comprehensions and just play with lists:

>>> foo = [1,2]
>>> bar = [3,4]
>>> result = foo.extend(bar)
>>> print foo
[1, 2, 3, 4]
>>> print bar
[3, 4]
>>> print result
None

Upvotes: 2

Related Questions