Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending specific integers to nested lists - Python

I have a nested list, A = [[1, 2, 3], [5, 2, 7], [4, 8, 9]]. I want to add the numbers 1, 2, 3 in list A to be A = [[1, 2, 3, 1], [5, 2, 7, 2], [4, 8, 9, 3]] and so on (this is just a shorter version). I tried the same using the code I wrote:

i = 0
j = 0
#number_nests = number of nested lists
for i in range(0, number_nests):
    for j in A:
        j.append(i)

print(A)

This is the output which I am getting, since I am a newbie, I am a little stuck: [[1, 90, 150, 0, 1, 2, 3], [2, 100, 200, 0, 1, 2, 3], [4, 105, 145, 0, 1, 2, 3], [3, 110, 190, 0, 1, 2, 3]]. I am trying to do it without numpy.

like image 329
quarters Avatar asked Jan 09 '23 07:01

quarters


2 Answers

A = [[1, 2, 3], [5, 2, 7], [4, 8, 9]]
i=1
for val in A:
    val.append(i)
    i += 1
like image 73
sachin saxena Avatar answered Jan 14 '23 11:01

sachin saxena


Simply iterate over the outer list along with the indexes, using enumerate:

for i, elem_list in enumerate(A, start=1):
    elem_list.append(i)
like image 36
shx2 Avatar answered Jan 14 '23 10:01

shx2