DEV Community

Cover image for Python Tuples
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

Python Tuples

A tuple is an immutable ordered collection of elements.

Tuples are similar to lists, but unlike lists, they cannot be changed after their creation.
Can hold elements of different data types.
These are ordered, heterogeneous and immutable.

Creating a Tuple

A tuple is created by placing all the items inside parentheses (), separated by commas. A tuple can have any number of items.

tup = ()
print(tup)

# Using String
tup = ('Geeks', 'For')
print(tup)

# Using List
li = [1, 2, 4, 5, 6]
print(tuple(li))

# Using Built-in Function
tup = tuple('Geeks')
print(tup)
Enter fullscreen mode Exit fullscreen mode

Output

()
('Geeks', 'For')
(1, 2, 4, 5, 6)
('G', 'e', 'e', 'k', 's')
Enter fullscreen mode Exit fullscreen mode

Creating a Tuple with Mixed Datatypes

Tuples can store elements of different data types, such as integers, strings, lists and dictionaries, within a single structure.

tup = (5, 'Welcome', 7.5, True, [1, 2, 3], {'key': 'value'})
print(tup)
tup = (5, 'Welcome', 7.5, True, [1, 2, 3], {'key': 'value'})
print(tup)
Enter fullscreen mode Exit fullscreen mode

Output

(5, 'Welcome', 7.5, True, [1, 2, 3], {'key': 'value'})
Enter fullscreen mode Exit fullscreen mode

Tuple Basic Operations

We can access the elements of a tuple by using indexing and slicing, similar to how we access elements in a list. Indexing starts at 0 for the first element and goes up to n-1, where n is the number of elements in the tuple. Negative indexing starts from -1 for the last element and goes backward.

tup = tuple("Geeks")
print(tup[0])
print(tup[1:4])  
print(tup[:3])

# Tuple unpacking
tup = ("Geeks", "For", "Geeks")

# This line unpack values of Tuple1
a, b, c = tup
print(a)
print(b)
print(c)
tup = tuple("Geeks")
print(tup[0])
print(tup[1:4])  
print(tup[:3])
​
# Tuple unpacking
tup = ("Geeks", "For", "Geeks")
​
# This line unpack values of Tuple1
a, b, c = tup
print(a)
print(b)
print(c)
Enter fullscreen mode Exit fullscreen mode

Output

G
('e', 'e', 'k')
('G', 'e', 'e')
Geeks
For
Geeks
Enter fullscreen mode Exit fullscreen mode

Concatenation of Tuples

Tuples can be concatenated using the + operator. This operation combines two or more tuples to create a new tuple.

Top comments (0)