4

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.

1
  • no need of range(0, number_nests), 0 is default start in range.So simply range(number_nests) Commented May 28, 2015 at 7:13

5 Answers 5

3
A = [[1, 2, 3], [5, 2, 7], [4, 8, 9]]
i=1
for val in A:
    val.append(i)
    i += 1
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

3

You can use enumerate built-in function with start parameter as 1 to get current index.

A = [[1, 2, 3], [5, 2, 7], [4, 8, 9]]

print([val+[i] for i, val in enumerate(A, 1)])

Using map built-in function

In python 2.x

print map(lambda x,y: x+[y],  A, range(1, len(A)+1))

In python 3.x

print(list(map(lambda x,y: x+[y], A, range(1, len(A)+1))))

Comments

1
A = [[1, 2, 3], [5, 2, 7], [4, 8, 9]]
B = [1, 2, 3]
print [A[i]+[B[i]] for i in range(len(A))]
#Output[[1, 2, 3, 1], [5, 2, 7, 2], [4, 8, 9, 3]]

Comments

-1

You only need one loop to add one number to each list in A:

for i in range(1, len(A)+1):
    A[i].append(i)

Note: the range should start at 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.