How to add elements in a list in list?

Question:

i am a beginner in python.

i have a list in list and i simply want to add an element in each sub-list at the last.

a = [ [0, 1 ,-1, 2, -2, 3, -3, 4, -4, -5, 5, 8], [0, 6 ,-6, 7, -7, 8, -8, 9, -9, -10, 10,  9] ]

for i in a:
    b = i.append(0)                         #want to add zero at the last of each sublist.
print(b)

each time output shows None (Null value)

Asked By: walter white

||

Answers:

You are almost there:

for i in a:
    i.append(0)                         #want to add zero at the last of each sublist.
print(a)

The append modifies the existing list in the list, so no need to use the b variable

Answered By: Andreas

Your code is correct but your understanding of list operation is wrong

lst = [1,2,3]
print(lst.append(4))  # None as the append method will return None
print(lst)  #[1, 2, 3, 4]

https://docs.python.org/3/tutorial/datastructures.html

a = [ [0, 1 ,-1, 2, -2, 3, -3, 4, -4, -5, 5, 8], [0, 6 ,-6, 7, -7, 8, -8, 9, -9, -10, 10,  9] ]

for i in a:
    i.append(0)  #want to add zero at the last of each sublist.
print(a)  # [[0, 1, -1, 2, -2, 3, -3, 4, -4, -5, 5, 8, 0], [0, 6, -6, 7, -7, 8, -8, 9, -9, -10, 10, 9, 0]]
Answered By: Deepan
a = [ [0, 1 ,-1, 2, -2, 3, -3, 4, -4, -5, 5, 8], [0, 6 ,-6, 7, -7, 8, -8, 9, -9, -10, 10,  9] ]
x = list(map(lambda x: x + [0], a))
print(x)
Answered By: tabish munir
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.