Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list appending is not working [duplicate]

Tags:

python

I have something similar to:

>>> S=list()
>>> T=[1,2,3]
>>> for t in T:
...     print(S.append(t))

The output I am getting is:

...
None
None
None

I expect S contains t. Why this is not working with me ?

like image 525
user2192774 Avatar asked Aug 26 '26 14:08

user2192774


1 Answers

list.append() does not return anything. Because it does not return anything, it default to None (that is why when you try print the values, you get None).

It simply appends the item to the given list in place. Observe:

>>> S = list()
>>> T = [1,2,3]
>>> for t in T:
...     S.append(t)
>>> print(S)
[1, 2, 3]

Another example:

>>> A = []
>>> for i in [1, 2, 3]:
...     A.append(i) # Append the value to a list
...     print(A) # Printing the list after appending an item to it
... 
[1]
[1, 2]
[1, 2, 3]
like image 194
TerryA Avatar answered Aug 28 '26 04:08

TerryA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!