DEV Community

Sowntharya
Sowntharya

Posted on

Python Tuple Tricks: Packing, Unpacking, Slicing

Tuple
In Python, a tuple is a collection of elements similar to a list. The main difference is that a tuple is immutable, which means we cannot directly modify, add or remove its elements after creation.

Tuples are useful when we want to store multiple values together and keep the data unchanged.

1. Creating a Tuple
A tuple can be created by separating values with commas. Parentheses are optional in many cases.

t = 1234, 54321, 'hello'

print(t[0])
print(t)
print(len(t))
print(type(t))

Enter fullscreen mode Exit fullscreen mode

Output:
1234
(1234, 54321, 'hello')
3

  • t[0] accesses the first element.
  • len(t) returns the number of elements.
  • type(t) identifies the data type as a tuple.

2. Nested Tuples
A tuple can contain another tuple inside it. This is called a nested tuple.

t = 1234, 54321, 'hello'

u = t, (1, 2, 3, 4, 5)
print(u)
Enter fullscreen mode Exit fullscreen mode

Output:
((1234, 54321, 'hello'), (1, 2, 3, 4, 5))

Explanation: The tuple u contains two elements: the original tuple t and another tuple containing numbers from 1 to 5.

3. Tuple Immutability
Tuples are immutable. Once a tuple is created, its elements cannot be changed directly.

t = (10, 20, 30)

# t[0] = 88888

Enter fullscreen mode Exit fullscreen mode

Error: TypeError: 'tuple' object does not support item assignment

We cannot assign a new value to an existing tuple element.

4. Tuples Can Contain Mutable Objects
Although a tuple is immutable, it can contain mutable objects such as lists.

v = ([1, 2, 3], [3, 2, 1])

v[0].append(4)

print(v)
Enter fullscreen mode Exit fullscreen mode

Output:
([1, 2, 3, 4], [3, 2, 1])

Explanation: We cannot replace the list stored inside the tuple, but we can modify the list itself because lists are mutable.

5. Tuple Packing and Unpacking
Tuple packing: Packing means combining multiple values into a single tuple.

t = 10, 20, 30, 'ABCD', True, 5.2

print(t)
Enter fullscreen mode Exit fullscreen mode

Output:
(10, 20, 30, 'ABCD', True, 5.2)

Tuple unpacking: Unpacking means assigning tuple elements to individual variables.

t = 10, 20, 30, 'ABCD', True, 5.2

e1, e2, e3, e4, e5, e6 = t

print(e4)
print(e5)
Enter fullscreen mode Exit fullscreen mode

Output:
ABCD
True

Explanation: Each element of the tuple is assigned to its corresponding variable.

6. Converting a List into a Tuple
We can convert a list into a tuple using the tuple() function.

l = [10, 20, 30]

t = tuple(l)

print(t)
print(type(t))
Enter fullscreen mode Exit fullscreen mode

Output:
(10, 20, 30)

This conversion is useful when we want to keep the collection from being directly modified.

7. Creating a Tuple Using range()
We can create a tuple containing numbers from 1 to 10 using range() and tuple().

t = tuple(range(1, 11))

print(t)
Enter fullscreen mode Exit fullscreen mode

Output:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Explanation: range(1, 11) generates numbers from 1 to 10, and tuple() converts those numbers into a tuple.

8. Tuple Indexing and Slicing
Tuple indexing and slicing are similar to list indexing and slicing.

t = tuple(range(1, 11))

print(t[-1])
print(t[2:5])
print(t[2:8:2])
print(t[::3])
Enter fullscreen mode Exit fullscreen mode

Output:
10
(3, 4, 5)
(3, 5, 7)
(1, 4, 7, 10)

Expression
t[-1] - Access the last element
t[2:5] - Get elements from index 2 to 4
t[2:8:2] - Get elements from index 2 to 7 with step 2
t[::3] - Get every third element

9. Tuple Concatenation and Repetition
Tuples support concatenation using + and repetition using .
**Concatenation
*

t1 = (10, 20, 30)
t2 = (40, 50, 60)
print(t1 + t2)
Enter fullscreen mode Exit fullscreen mode

Output:
(10, 20, 30, 40, 50, 60)

Repetition

t1 = (10, 20, 30)
print(t1 * 3)
Enter fullscreen mode Exit fullscreen mode

Output:
(10, 20, 30, 10, 20, 30, 10, 20, 30)

10. Difference Between == and is

  • == checks whether two objects have equal values.
  • is checks whether two variables refer to the same object in memory.
l1 = (10, 20, 30)
l2 = l1
l3 = tuple(l1)

print(id(l1))
print(id(l2))
print(id(l3))

print(l1 == l2)
print(l1 is l2)

print(l1 == l3)
print(l1 is l3)

Enter fullscreen mode Exit fullscreen mode

Output (Boolean values):
True
True
True
True

note: In this example, tuple(l1) returns the same tuple object when l1 is already a tuple. So l3 may refer to the same object as l1, and l1 is l3 is True. The id() values help illustrate object identity.

Operator Purpose
== Checks value equality
is Checks object identity

11. Tuple Methods and Built-in Functions
Tuples have only two built-in methods because they are immutable.

Method / Function Purpose
count() - Counts how many times a value occurs
index() - Returns the index of a value
len() - Returns the number of elements
min() - Returns the smallest element
max() - Returns the largest element
sorted() - Returns a sorted list of elements

Example:

t = (10, 20, 10, 30, 40)

print(t.count(10))
print(t.index(30))
print(len(t))
print(min(t))
print(max(t))
print(sorted(t))
Enter fullscreen mode Exit fullscreen mode

Output:
2
3
5
10
40
[10, 10, 20, 30, 40]

Note: sorted() returns a list, not a tuple.

12. Is Tuple Comprehension Possible?
Python does not have a dedicated tuple comprehension syntax like list comprehension.

List comprehension

l = [no for no in range(1, 11)]
print(l)
Enter fullscreen mode Exit fullscreen mode

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generator expression

t = (no for no in range(1, 11))
print(t)
Enter fullscreen mode Exit fullscreen mode

Output:
generator object at ...

Why? Parentheses containing a comprehension create a generator expression, not a tuple.

To convert it into a tuple:

t = (no for no in range(1, 11))
print(tuple(t))
Enter fullscreen mode Exit fullscreen mode

Output:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Explanation: A generator expression generates values one at a time. Using tuple() consumes the generator and creates a tuple containing those values.

13. List vs Tuple

Conclusion
Tuples are an important data structure in Python. They help store multiple values in a single collection while preventing direct modification of the tuple's elements.

Top comments (0)