Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Defining Tuples

Give Feedback

In this lesson, you’ll explore defining and using tuples. Tuples are identical to lists in all respets, except two. They are immutable and are defined by enclosing the elements in parentheses instead of square brackets:

a = ('spam', 'egg', 'bacon', 'tomato')

Here’s why you would choose to use a tuple instead of list:

  • Program execution is faster when manipulating a tuple than it is for the equivalent list.
  • You don’t want data modified.
  • A Python dicionary requires keys that are of an immutable type.

Here’s an example:

>>>
>>> t = ('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>> t
('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>> type(t)
<class 'tuple'>

>>> t[0]
'spam'
>>> t[-1]
'lobster'
>>> t[3:6]
('tomato', 'ham', 'lobster')
>>> t[1:4]
('egg', 'bacon', 'tomato')
>>> t[0:6:2]
('spam', 'bacon', 'ham')
>>> t[::-1]
('lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam')

>>> t
('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>> t[2]
'bacon'
>>> t[2] = 'butter'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    t[2] = 'butter'
TypeError: 'tuple' object does not support item assignment

>>> a = 'spam'
>>> b = 42
>>> a, 3.14159, b
('spam', 3.14159, 42)
>>> t = ()
>>> type(t)
<class 'tuple'>
>>> t
()

>>> t = (1, 2)
>>> type(t)
<class 'tuple'>
>>> t = (2)
>>> t
2
>>> type(t)
<class 'int'>

>>> t = (2, )
>>> type(t)
<class 'tuple'>
>>> t
(2,)

Comments & Discussion

Pygator on Sept. 29, 2019

Never thought about singleton tuples, never tried to make such a tuple in all my years of python programming!

Become a Member to join the conversation.