Here is a formatted and highlighted summary of Python tuples, ready to copy.
Python Tuples
A tuple is a collection used to store multiple items in a single variable. Tuples are one of
Python's 4 built-in collection data types (along with List, Set, and Dictionary).
• Key Properties: A tuple is a collection which is ordered and unchangeable (immutable).
• Syntax: Tuples are written with round brackets ().
Python
# Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Core Characteristics
Tuple Items
Tuple items have three main characteristics:
1. Ordered: The items have a defined order that will not change.
2. Unchangeable: You cannot change, add, or remove items after the tuple has been
created.
3. Allow Duplicates: Since tuples are indexed, they can contain items with the same value.
Python
# Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To get the number of items in a tuple, use the len() function.
Python
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
# Output: 3
Create Tuple With One Item
This is a common point of confusion. To create a tuple with only one item, you must add a
comma after the item.
Python
# A tuple (note the comma)
thistuple = ("apple",)
print(type(thistuple))
# Output: <class 'tuple'>
# NOT a tuple (this is just a string)
thistuple = ("apple")
print(type(thistuple))
# Output: <class 'str'>
Data Types
Tuple items can be of any data type, and a single tuple can contain a mix of different data
types.
Python
# A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
The tuple() Constructor
You can also create a tuple using the tuple() constructor. (Note the double round-brackets).
Python
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)
Python Collection Types
• List: Ordered and changeable. Allows duplicate members. []
• Tuple: Ordered and unchangeable. Allows duplicate members. ()
• Set: Unordered and unindexed. No duplicate members. {}
• Dictionary: Ordered (as of Python 3.7) and changeable. No duplicate keys. {key: value}
Accessing Items
Access by Index
Access items by using their index number inside square brackets [].
Note: The first item has index [0].
Python
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
# Output: "banana"
Negative Indexing
Negative indexing starts from the end. -1 is the last item, -2 is the second-to-last, etc.
Python
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
# Output: "cherry"
Range of Indexes (Slicing)
Slicing lets you get a range of items, which returns a new tuple.
The syntax is [start:end].
• The start index is included.
• The end index is excluded.
Python
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
# Return the third, fourth, and fifth item:
print(thistuple[2:5])
# Output: ('cherry', 'orange', 'kiwi')
# From the beginning to index 4 (not included):
print(thistuple[:4])
# Output: ('apple', 'banana', 'cherry', 'orange')
# From index 2 to the end:
print(thistuple[2:])
# Output: ('cherry', 'orange', 'kiwi', 'melon', 'mango')
# Negative range:
print(thistuple[-4:-1])
# Output: ('orange', 'kiwi', 'melon')
Check if Item Exists
Use the in keyword to check if an item is present in a tuple.
Python
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Updating Tuples (Workaround)
Because tuples are immutable, you cannot change them directly.
The Workaround: You must convert the tuple to a list, make your changes, and then convert the
list back into a tuple.
Change Tuple Values
Python
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
# Output: ('apple', 'kiwi', 'cherry')
Add Items
1. Convert to a list:
Python
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)
2. Add tuple to a tuple (Concatenation):
You can add two tuples together using the + operator.
Python
thistuple = ("apple", "banana", "cherry")
y = ("orange",) # Note the comma!
thistuple += y
print(thistuple)
# Output: ('apple', 'banana', 'cherry', 'orange')
Remove Items
You cannot remove items from a tuple.
• Use the same list conversion workaround.
• Or, you can delete the tuple completely with the del keyword.
Python
thistuple = ("apple", "banana", "cherry")
del thistuple
# print(thistuple) # This will raise an error because the tuple no longer exists
Unpacking Tuples
Packing is when we assign values to a tuple.
fruits = ("apple", "banana", "cherry")
Unpacking is when we extract those values back into variables.
Python
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green) # Output: apple
print(yellow) # Output: banana
print(red) # Output: cherry
Note: The number of variables must match the number of values in the tuple.
Using Asterisk *
If the number of variables is less than the number of values, use an asterisk * on a variable
name. This variable will receive the remaining values as a list.
Python
# Using * on the last variable
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green) # Output: apple
print(yellow) # Output: banana
print(red) # Output: ['cherry', 'strawberry', 'raspberry']
Python
# Using * on a middle variable
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green) # Output: apple
print(tropic) # Output: ['mango', 'papaya', 'pineapple']
print(red) # Output: cherry
Looping
for Loop
Iterate through the items and print the values.
Python
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Loop Through Index Numbers
You can also loop using range() and len().
Python
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
while Loop
Python
thistuple = ("apple", "banana", "cherry")
i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1
Joining & Multiplying
Join Two Tuples (+)
Use the + operator to combine two tuples into a new one.
Python
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
# Output: ('a', 'b', 'c', 1, 2, 3)
Multiply Tuples (*)
Use the * operator to multiply the content of a tuple.
Python
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
# Output: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
Tuple Methods
Tuples have only two built-in methods because they are immutable.
count()
Returns the number of times a specified value appears in the tuple.
Python
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](5)
print(x)
# Output: 2
index()
Searches the tuple for a specified value and returns the position of its first occurrence.
Python
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](8)
print(x)
# Output: 3