Valinor
Valinor

Reputation: 17

List.append() under a loop in a list can't get a right ouput

Usually I do it like this:

a=[]
for x in range(5):
    a.append(x)
print(a)
# [0, 1, 2, 3, 4]

then I put the loop in a list

a=[]
L=[a.append(x) for x in range(5)]
print(L)
# [None, None, None, None, None]

I don't konw what's wrong with it...

Upvotes: 0

Views: 55

Answers (2)

Kester
Kester

Reputation: 283

That is because the x is added to a but not L.

    a=[]
    L=[a.append(x) for x in range(5)]
    print(L)
    # [None, None, None, None, None]
    # print(a) will show what you want. 

Upvotes: 0

Jonas Adler
Jonas Adler

Reputation: 10810

The problem here is that a.append(x) is a method of the list a which modifies a in place. It returns None.

Interestingly you get this:

a=[]
L=[a.append(x) for x in range(5)]
print(L)
# [None, None, None, None, None]
print(a)
# [0, 1, 2, 3, 4]

Note that a was updated. However, using list comprehensions like this for their side effects is not recommended since the code becomes very hard to understand.

If you want to create L using a list comprehension you should do this:

L = [x for x in range(5)]
print(L)
# [0, 1, 2, 3, 4]

The best code would hovever be simply

L = list(range(5))
print(L)
# [0, 1, 2, 3, 4]

Upvotes: 2

Related Questions