Tuples
A tuple in Python is an immutable, ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types and are defined by enclosing the elements in parentheses.
Tuples are commonly used in Python for returning multiple values from functions, as dictionary keys (when they contain only immutable elements), and for representing fixed collections of data that should not be modified, such as days of the week or coordinates. Their immutability makes them more memory efficient and faster than lists for large data.
Key Characteristics of Tuples
- Ordered: Elements in a tuple maintain a defined order, which can be accessed by index.
- Immutable: Once created, elements in a tuple cannot be added, removed, or modified.
- Heterogeneous: A tuple can contain elements of different data types, including other tuples.
- Indexed: Elements in a tuple can be accessed using zero-based indexing.
- Nestable: Tuples can contain other tuples, creating nested structures.
- Iterable: Tuples can be iterated through using loops.
Creating Tuples
There are several ways to create tuples in Python:
Using Parentheses
The most common way to create a tuple is by placing elements inside parentheses ()
, separated by commas:
# Creating a tuple with different data typesmixed_tuple = (1, "Hello", 3.14, True)print(mixed_tuple)Copy to clipboardCopy to clipboard
The output of this code will be:
(1, 'Hello', 3.14, True)Copy to clipboardCopy to clipboard
Without Parentheses (Tuple Packing)
Python allows tuple creation without parentheses, simply by separating items with commas. This is known as tuple packing:
# Creating a tuple without parenthesescoordinates = 10.5, 20.7, 30.9print(coordinates)print(type(coordinates))Copy to clipboardCopy to clipboard
The output of this code will be:
(10.5, 20.7, 30.9)<class 'tuple'>Copy to clipboardCopy to clipboard
Empty Tuple
To create an empty tuple, use empty parentheses()
:
# Creating an empty tupleempty_tuple = ()print(empty_tuple)print(type(empty_tuple))Copy to clipboardCopy to clipboard
The output of this code will be:
()<class 'tuple'>Copy to clipboardCopy to clipboard
Single-Element Tuple
Creating a tuple with just one element requires a trailing comma, otherwise, Python interprets it as a regular expression in parentheses:
# Incorrect way - this is not a tuplenot_a_tuple = (42)print(not_a_tuple)print(type(not_a_tuple))# Correct way - with trailing commasingle_element_tuple = (42,)print(single_element_tuple)print(type(single_element_tuple))Copy to clipboardCopy to clipboard
The output of this code will be:
42<class 'int'>(42,)<class 'tuple'>Copy to clipboardCopy to clipboard
Using the tuple()
Constructor
The tuple()
function can convert other iterable objects like lists, strings, or dictionaries (keys) into tuples:
# Creating tuples from other iterablestuple_from_list = tuple([1, 2, 3, 4])tuple_from_string = tuple("Python")tuple_from_range = tuple(range(5))print(tuple_from_list)print(tuple_from_string)print(tuple_from_range)Copy to clipboardCopy to clipboard
The output of this code will be:
(1, 2, 3, 4)('P', 'y', 't', 'h', 'o', 'n')(0, 1, 2, 3, 4)Copy to clipboardCopy to clipboard
Accessing Tuple Elements
Tuple elements can be accessed using indexing, similar to lists. Indexing starts at 0 for the first element.
Using Positive Indexing
# Accessing elements with positive indexingcolors = ('red', 'green', 'blue', 'yellow', 'purple')print(colors[0]) # First elementprint(colors[2]) # Third elementCopy to clipboardCopy to clipboard
The output of this code will be:
redblueCopy to clipboardCopy to clipboard
Using Negative Indexing
Negative indexing allows access from the end of the tuple. The last element is at index -1, the second-to-last at -2, and so on:
# Accessing elements with negative indexingcolors = ('red', 'green', 'blue', 'yellow', 'purple')print(colors[-1]) # Last elementprint(colors[-3]) # Third-to-last elementCopy to clipboardCopy to clipboard
The output of this code will be:
purpleblueCopy to clipboardCopy to clipboard
Tuple Operations
Concatenation
Tuples can be concatenated using the +
operator to create a new tuple:
# Concatenating tuplestuple1 = (1, 2, 3)tuple2 = ('a', 'b', 'c')concatenated = tuple1 + tuple2print(concatenated)Copy to clipboardCopy to clipboard
The output of this code will be:
(1, 2, 3, 'a', 'b', 'c')Copy to clipboardCopy to clipboard
Repetition
Tuples can be repeated using the *
operator:
# Repeating a tuplerepeated = (1, 2, 3) * 3print(repeated)Copy to clipboardCopy to clipboard
The output of this code will be:
(1, 2, 3, 1, 2, 3, 1, 2, 3)Copy to clipboardCopy to clipboard
Membership Testing
Checking if an element exists in a tuple can be done using the in
keyword.
# Checking membershipfruits = ('apple', 'banana', 'orange', 'grape')print('banana' in fruits)print('mango' in fruits)Copy to clipboardCopy to clipboard
The output of this code will be:
TrueFalseCopy to clipboardCopy to clipboard
Slicing of Tuple
Slices allow for the extraction of a portion of a tuple using the syntax tuple[start:stop:step]
:
# Slicing a tuplenumbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)print(numbers[2:7]) # Elements from index 2 to 6print(numbers[::2]) # Every second elementprint(numbers[::-1]) # Reversed tupleCopy to clipboardCopy to clipboard
The output of this code will be:
(2, 3, 4, 5, 6)(0, 2, 4, 6, 8)(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)Copy to clipboardCopy to clipboard
Deleting a Tuple
Since tuples are immutable, individual elements cannot be deleted. However, the entire tuple can be deleted using the del
keyword:
# Deleting a tuplecoordinates = (10.5, 20.7, 30.9)del coordinates# print(coordinates) # This would raise a NameErrorCopy to clipboardCopy to clipboard
Frequently Asked Questions
1. Which of the following is a Python tuple: 4 5 6
, (4 5 6)
, [4, 5, 6]
, {4, 5, 6}
?
Only (4, 5, 6)
is a valid Python tuple. The notation 4 5 6
without commas is a syntax error, [4, 5, 6]
is a list, and {4, 5, 6}
is a set.
2. What is the difference between a tuple and a list?
The main differences between tuples and lists are:
- Mutability: Tuples are immutable (cannot be changed after creation), while lists are mutable (can be modified).
- Syntax: Tuples use parentheses
()
, while lists use square brackets[]
. - Performance: Tuples are slightly faster and use less memory than lists.
- Usage: Tuples are typically used for heterogeneous data (different types), while lists are used for homogeneous items (similar types).
- Methods: Lists have more built-in methods because they’re mutable (e.g.,
append()
,insert()
,remove()
).
3. Can you edit a tuple?
No, tuples cannot be edited after creation because they are immutable. Once a tuple is created, you cannot add, remove, or change its elements. If you need to modify the data, you must create a new tuple:
# Converting to list, modifying, and converting back to tupleoriginal = (1, 2, 3, 4)temp_list = list(original)temp_list[1] = 20modified = tuple(temp_list)print(modified)Copy to clipboardCopy to clipboard
The output of this code will be:
(1, 20, 3, 4)Copy to clipboardCopy to clipboard
4. How to sort a tuple in Python?
Since tuples are immutable, you cannot sort a tuple in-place like you can with lists. You have two options:
1. Create a new sorted tuple using the sorted()
function:
# Creating a new sorted tupleunsorted = (5, 2, 8, 1, 9, 3)sorted_tuple = tuple(sorted(unsorted))print(sorted_tuple)Copy to clipboardCopy to clipboard
Output:
(1, 2, 3, 5, 8, 9)Copy to clipboardCopy to clipboard
2. To sort in descending order, add the reverse=True
parameter:
# Sorting in descending orderunsorted = (5, 2, 8, 1, 9, 3)sorted_desc = tuple(sorted(unsorted, reverse=True))print(sorted_desc)Copy to clipboardCopy to clipboard
Output:
(9, 8, 5, 3, 2, 1)Copy to clipboardCopy to clipboard
Tuples
- .count()
- Returns the number of occurrences of a specific value in a tuple.
- .index()
- Returns the index of the first occurrence of a specific value in a tuple.
All contributors
- Preview: Anonymous contributor 3126 total contributionsAnonymous contributor
3126 total contributions
- MamtaWardhani
- sczerman
- BrandonDusch
- christian.dinh
- Anonymous contributor
- AndrewBarbour
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours