2

this is the code I have:

l = [[1,'a'],[2,'b'],[3,'c']]
n = []
for i in range(len(l)):
  n.append(l[i])
print(n)

I'm trying to select each element in the array to revers the number order only and putting it into a new array.

so I'm trying to get it to look like this:

[[3,'a'],[2,'b'],[1,'c']]
1
  • @blhsing's answer is fine as far as it goes. But since your question lacks enough context to know why you need that transformation it is impossible to know if that is a good answer. Especially in light of your solution which does nothing more than copy the l list to n with no transformation whatsoever. Commented Nov 6, 2018 at 3:11

1 Answer 1

2

You can pair the reversed list with the list itself using zip in a list comprehension like this:

[[a, b] for (a, _), (_, b) in zip(reversed(l), l)]

This returns:

[[3, 'a'], [2, 'b'], [1, 'c']]

Or you can modify the list in-place by swapping items:

for i in range(len(l) // 2):
    l[i][0], l[len(l) - i - 1][0] = l[len(l) - i - 1][0], l[i][0]

l would become:

[[3, 'a'], [2, 'b'], [1, 'c']]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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