Tuples are store multiple items in a single variable in Python. A tuple is an immutable object meaning that we cannot change, add or remove items after the tuple has been created.
empty_tuple = ()
mytuple = ("apple", "banana", "cherry")
Python Tuples are used to store collections of data, and their other data type is List, Set, and Dictionary, all with different qualities and usage.
In Python, a tuple is an ordered, immutable collection of elements enclosed in parentheses ()
. It is a data structure similar to a list, but unlike lists, tuples cannot be modified once created. Tuples can contain elements of different types, such as numbers, strings, or even other tuples.
How to create and use tuples in Python
Simple example code creating non-empty tuples. Tuples that are ordered will not change, are unchangeable, and Allow Duplicates.
# One way of creation
tup = 'A', 'B'
print(tup)
# Another for doing the same
tup = ('X', 'Y')
print(tup)
Output:
Accessing tuple elements: You can access individual elements of a tuple using indexing. Python uses zero-based indexing, so the first element is at index 0. Here’s an example:
print(my_tuple[0]) # Output: 1
How Tuple assignment: You can assign the elements of a tuple to multiple variables in a single statement. Here’s an example:
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
Tuple concatenation: You can concatenate tuples using the +
operator. It creates a new tuple that combines the elements of the original tuples.
tuple1 = (1, 2)
tuple2 = (3, 4)
combined_tuple = tuple1 + tuple2
print(combined_tuple) # Output: (1, 2, 3, 4)
Iterating over a tuple: You can use a for
loop to iterate over the elements of a tuple. Here’s an example:
my_tuple = (1, 2, 3)
for element in my_tuple:
print(element)
Use Tuple methods: Tuples have a few built-in methods, such as count()
and index()
. The count()
method returns the number of occurrences of a specific element in the tuple, while the index()
method returns the index of the first occurrence of a specific element. Here’s an example:
my_tuple = (1, 2, 2, 3, 3, 3)
print(my_tuple.count(2)) # Output: 2
print(my_tuple.index(3)) # Output: 3
In this case, the count()
method returns 2 since the value 2 appears twice in the tuple, and the index()
method returns 3, which is the index of the first occurrence of 3.
Comment if you have any doubts or suggestions on this Python tuple basics tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.