Python Tuples

Tuples are similar to lists with one distinction, tuples are immutable. Immutable means you cannot change items of a tuple (you cannot add new items, you cannot remove items or change values of existing items). You can use tuples to create a constant collection of items.

You can create a tuple you using parentheses instead of square brackets.

departments = ("sales", "marketing", "services")

# tuples are used to create constant collections

Tuple Containing One Value

To create a tuple containing only one value, type your value inside parenthesis. After your value, you should put a comma to create a valid tuple.

To create an empty tuple, you should just open and close parenthesis.

count = (5,)
# count variable is a tuple containing one value (5)
# If you omit comma, type of count variable will be int
# instead of tuple

empty_tuple=()
# just open and close parenthesis to create an empty tuple

Accessing Items in a Tuple

You can access items in tuples similar to lists. Type the index of the item you want to access inside square brackets.

colors = ("red", "blue", "yellow")
print("First item of colors tuple is : " + colors[0])

# First item of colors tuple is : red

Updating Items in a Tuple

You cannot update items in a tuple, because tuples are immutable. If you try to update an item, you will get an error.

colors = ("red", "blue", "yellow")
colors[0] = "green"

# You cannot update items in tuples.
# This assignment statement gives the following error:
# TypeError: 'tuple' object does not support item assignment

Tuples are designed to create immutable collections. Still, there is a way to update an item. First, convert your immutable tuple to a mutable list. Then, update the item and convert it back to a tuple.

colors = ("red", "blue", "yellow")
listColors = list(colors)
listColors[0] = "green"
colors = tuple(listColors)

# New tuple is  : ("green", "blue", "yellow")

Slicing

Slicing in tuples is similar to slicing in lists. Specify the start index and end index of your slice. Start index is inclusive, end index is exclusive.

colors = ("Red", "Blue", "Yellow", "Green", "Orange")
print(colors[1:4])

# ["Blue", "Yellow", "Green"]
# start index is 1 ("Blue") (inclusive)
# end index is 4 ("Orange") (exclusive)

Iterating a Tuple

To iterate items in a tuple, you can use a for loop.

colors = ("red", "blue", "yellow")
for color in colors:
  print("color is : " + color)

# prints:
# color is : red
# color is : blue
# color is : yellow

Adding/Removing Items

You cannot add/remove items in tuples since tuples are immutable and cannot be changed. If you need a dynamic collection of items you should use lists.

Checking Item for Existence

To check the existence of an item in a tuple, you can use IN membership operator.

colors = ("red", "blue", "yellow")
if "red" in colors:
   print("red is in colors tuple.")