0

I have a 2D list and want to change one of the values inside of it

I have tried converting to a list and back again. But i do not think that is what I am looking for.

a = [(3, 12, .05), (6, 1, .3)]
a[0][2] = 543
1
  • Why not use a list of lists? Commented Sep 10, 2019 at 5:19

2 Answers 2

3

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

a = [(3, 12, .05), (6, 1, .3)]
y = list(a[0])
y[2] = 543
a[0] = tuple(y)
print a
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I know similar questions had been asked but your answer was exactly what I needed I was trying to turn the whole thing into a list like y = a[0][1]. Thanks Heaps
I'm happy to help.
0

As @ShantesharInde said, tuples are unchangeable/immutable. They are declared by parentheses (). Lists are created by brackets []. So in your code a is a list of tuples. Two ways to make it changeable/mutable.

Method 1: Change declaration

>>> a = [[3, 12, .05], [6, 1, .3]]
>>> a[0][2] = 543
>>> a
[[3, 12, 543], [6, 1, 0.3]]

Method 2: convert inner tuples to lists

>>> a = [(3, 12, .05), (6, 1, .3)]
>>> for idx, item in enumerate(a):
...     a[idx] = list(item)
... 
>>> a[0][2] = 543 
>>> a
[[3, 12, 543], [6, 1, 0.3]]

The for loop with enumerate is a nice way of doing things if your list has many entries. For just two elements, you could just do

a[0] = list(a[0])
a[1] = list(a[1])

If you're wondering why converting to list didn't work for you before, it's because the list() function will only try to convert the outermost elements. So converting a list to a list has no effect.

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.