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.
A = [[1, 2, 3], [5, 2, 7], [4, 8, 9]]
i=1
for val in A:
val.append(i)
i += 1
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With