0

New to python and I´m trying to create a list from the lists created on for loop:

A = [[1,2,3],[4,3,2],[8,5,6]]
for l in range(len(A)):
    resultado = []
    A2 = A[l][::-1]
    resultado.append(A2)
    print(resultado)

The current output is:

[[3, 2, 1]]
[[2, 3, 4]]
[[6, 5, 8]]

I´m trying to make this:

 [[3, 2, 1],[2, 3, 4],[6, 5, 8]]
1
  • as you can see the needed result can be easily obtained with one line of code Commented Dec 29, 2016 at 17:42

4 Answers 4

6

Use a list comprehension:

[x[::-1] for x in A]
# [[3, 2, 1], [2, 3, 4], [6, 5, 8]]

You can also reverse the list in place:

for x in A: 
    x.reverse()

A
# [[3, 2, 1], [2, 3, 4], [6, 5, 8]]
Sign up to request clarification or add additional context in comments.

Comments

1

A list comprehension would work as well:

resultado = [l[::-1] for l in A]

Comments

0

Then use this following code

A = [[1,2,3],[4,3,2],[8,5,6]]
B=[]
for l in range(len(A)):
    A2 = A[l][::-1]
    B.append(A2)
print(B)

Answer : [[3, 2, 1],[2, 3, 4],[6, 5, 8]]

Comments

0

Adjust like below:

A = [[1,2,3],[4,3,2],[8,5,6]]
resultado = []

for l in range(len(A)):
    A2 = A[l][::-1]
    resultado.append(A2)

print(resultado)

resultado = [] inside your for loop, means for each iteration, you initialize resultado to []

Output:

>>> print(resultado)
[[3, 2, 1], [2, 3, 4], [6, 5, 8]]

Note: You can achieve the same result with a list comprehension and reversed():

>>> [list(reversed(item)) for item in A]
[[3, 2, 1], [2, 3, 4], [6, 5, 8]]

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.