-2

Example:

 a = (1,2,[3,4,5],6)

Can we make changes and make tuple a to give output as

>> (1,2,[3,0,5],6)?
Daniel Lee
  • 7,189
  • 2
  • 26
  • 44
Prasun Parate
  • 85
  • 1
  • 9
  • If you get a reference to the list then you can mutate that in place, eg: `a[2][:] = [3, 0, 5]` but not quite sure that's actually what you're asking... what's your use case here? – Jon Clements Apr 21 '20 at 11:16
  • `a[2][1] = 0` Will do what you want. To answer your actual question, Yes, we can change a list inside a tuple. – Daniel Lee Apr 21 '20 at 11:26

5 Answers5

1

Yes like this:

a=(1,2,[3,4,5],6)
a[2][1] = 0
print(a)

What this does is gets the third element of the tuple wich is the list then gives the new data to the second element in the list then prints out the whole tuple with the new data in the list. I believe this is what you want to do please tell me if it isnt thanks.

Zack Turner
  • 216
  • 3
  • 14
0

Yes you can, like this:

a=(1,2,[3,4,5],6) 
a[2][1]=0
print(a)

This takes the third element of a, which is the list and modifies each element in the list separately.

0

You might do it using pop and insert methods of that list

a = (1,2,[3,4,5],6)
a[2].pop(1)
a[2].insert(1, 0)
print(a)

Output:

(1, 2, [3, 0, 5], 6)

These methods acts in place, pop removes element at index 1 (indices are starting from 0), insert inserts before element at index 1 value 0.

Daweo
  • 31,313
  • 3
  • 12
  • 25
0

You can do this:

a=(1,2,[3,4,5],6) 
b = a[2]
b[1]=0
a

Output: (1, 2, [3, 0, 5], 6)

Sammiti Yadav
  • 78
  • 1
  • 6
-1

Python tuples are immutable. The only solution to change the content is to create a new tuple. Here note that your tuple element at index 2 stores an array, which is mutable by reference so you can mutate the array but not assigning a new array.

In other words:

t = (1, 2, [3, 4], 5)

# New tuple:
t = (1, 2, [3, 4, 5], 5) # or
t = (t[0], t[1], [3, 4, 5], t[3]) # to copy values

# Mutate the array:
t[2].append(5)

In your case:

a = (1, 2, [3, 4, 5], 6)
# Mutate the array
a[2][1] = 0
Louis Lac
  • 5,298
  • 1
  • 21
  • 36
  • Triples are immutable but objects inside a tuple are not. – rolf82 Apr 21 '20 at 11:35
  • Only reference types are mutable, you can't assign a new value to a tuple element, if `t = (1, 2, 3)` you cannot do `t[0] += 1` or `t[0] = 2`. And for reference types like arrays you can mutate the array but not the reference: if `t = (0, [1, 2], 3)` you cannot do `t[1] = [4, 5]`. – Louis Lac Apr 21 '20 at 11:42