Python Lesson 12: Tuples in Python

  1. Create a Tuple
  2. Access items in a Tuple
  3. Get the count of items in an Tuple
  4. Check if an item exists in a Tuple
  5. Loop through items in a Tuple
  6. Add items to a Tuple

Features of a Tuple

A tuple is a collection of objects. It contains the following features:

  • It is ordered
  • It is NOT changeable
  • It allows duplicate members
  • Smaller and faster than a list

1) Create a Tuple

#Create a tuple. Use parenthesis
workdays = ("Monday","Tuesday","Wednesday","Thursday","Friday")
print(workdays)
Notebook Output

2) Access items in a Tuple

Items in a tuple are accessed by index. You can also use slice notation.

#Get items in a Tuple
workdays = ("Monday","Tuesday","Wednesday","Thursday","Friday")
#Get the first item
print(workdays[0])
#Get the last item
print(workdays[-1])
#Get the items starting at position 1 and ending before position 3
print(workdays[1:3])
#Get the first 3 items
print(workdays[:3])
#Get all the items starting at position 2
print(workdays[2:])
Notebook Output

3) Get the count of items in an Tuple

To get the count of items in a Tuple use the len() method

#Get number of items in a tuple
workdays = ("Monday","Tuesday","Wednesday","Thursday","Friday")
print(len(workdays))
Notebook Output

4) Check if an item exists in a Tuple

To check if an item exists in a Tuple use the in keyword

workdays = ("Monday","Tuesday","Wednesday","Thursday","Friday")
"Monday" in workdays
Notebook Output

5) Loop through items in a Tuple

Use a for loop to loop though items in a Tuple.

workdays = ("Monday","Tuesday","Wednesday","Thursday","Friday")
for x in workdays:
    print(x)
Notebook Output

6) Add items to a Tuple

Tuples are not changeable. To add an item to a Tuple you must create a new Tuple.

#To add items to a tuple you must create a new Tuple
workdays = ("Monday","Tuesday","Wednesday","Thursday","Friday")
weekend = ("Saturday","Sunday")
daysofweek = workdays + weekend
print(daysofweek)
Notebook Output

Recommended Books