logo codesdope

Tuples in Python


Tuples are initiated as :

  • Python 2
  • Python 3
a = ()
a = (1,2,"Hello World!")
print a[0]
print a[1]
print a
a = ()
a = (1,2,"Hello World!")
print(a[0])
print(a[1])
print(a)
Output
1
2
(1, 2, 'Hello World!')

Yes, it is nearly the same as of a list and we can use len and slice also on a tuple it is immutable i.e., we can't change the value of any item of a tuple. Let's try this:

  • Python 2
  • Python 3
a = ()
a = (1,2,"Hello World!")
a [1] = 5
a = ()
a = (1,2,"Hello World!")
a [1] = 5
Output
a [1] = 5
TypeError: 'tuple' object does not support item assignment

This is the same error that you had got while trying to change the elements of a string. Since tuple is also not mutable like string, so we can't change the elements of a tuple.

We also can't use append on tuples.

Don't worry about failure. You only have to right once.
- Drew Houston

Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.