1

i can always change bwtween list if I do not have them in One array...

If I have an array having more than one list

 a = [[2,3,4,],[8,14,13],[12,54,98]]

how do I replace a[2] with a[0]??

Thanks in Advance

4 Answers 4

2

Lists are mutable so you probably want to replace list items, not the lists themselves:

a[2][:] = a[0]

If you want to swap lists rather than replace them then:

a[0], a[2] = a[2], a[0]
Sign up to request clarification or add additional context in comments.

Comments

1

For your original post:

a = [[2,3,4,],[8,14,13],[12,54,98]]
a[2] = a[0]

then a will be:

[[2, 3, 4], [8, 14, 13], [2, 3, 4]] 

Update based on comment to sdolan below:

If you want to exchange the two, you could simply do this:

a[0], a[-1] = a[-1], a[0]

giving

[[12, 54, 98], [8, 14, 13], [2, 3, 4]]

1 Comment

@charlottechahin one more update (even simpler to swap first and last element)
1

You can just assign it:

>>> a = [[2,3,4,],[8,14,13],[12,54,98]]
>>> 
>>> a[2] = list(a[0]) # list() to create a new copy
>>> a
[[2, 3, 4], [8, 14, 13], [2, 3, 4]]

1 Comment

hey thanks for the answer.. I missed something in my question I wanted to flip them... I would like to end up with a= [[12, 54, 98], [8, 14, 13], [2, 3, 4]]... Thanks again
0

The way you asked this is to just change the array from a = [[2,3,4,],[8,14,13],[12,54,98]] to a = [[2,3,4,],[8,14,13],[2,3,4,]]

so you can do a[2] = a[0]

but if you want to swap them, you will need something like:

b = a[0]
a[0] = a[2]
a[2] = b

EDIT for shorthand:

a[0], a[2] = a[2], a[0]

2 Comments

You don't need the intermediate b: a[0], a[2] = a[2], a[0] works. [Not that you can tell when they're equal..]
@charlottechahine don't forget to upvote anything you feel was helpful and mark an answer.

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.