Home > front end >  How to add elements in a list in list?
How to add elements in a list in list?

Time:08-06

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)

CodePudding user response:

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

CodePudding user response:

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]]
  • Related