Python TUPLE – Pack, Unpack, Compare, Slicing, Delete, Key

Created with Sketch.

A tuple in Python is an immutable, ordered collection of elements. Once a tuple is created, you cannot change its values or length. Here are various operations you can perform with tuples:

1. Creating a Tuple:

You can create a tuple using parentheses ().

my_tuple = (1, 2, 3, 'hello', 3.14)

2. Packing and Unpacking:

Packing: Assigning multiple values to a single variable creates a tuple.

packed_tuple = 1, 'apple', 3.14

Unpacking: Assigning tuple elements to multiple variables.

a, b, c = packed_tuple

3. Comparing Tuples:

Tuples can be compared element-wise.

tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)

if tuple1 == tuple2:
    print("Tuples are equal")
else:
    print("Tuples are not equal")

4. Slicing a Tuple:

 
my_tuple = (10, 20, 30, 40, 50)
subset_tuple = my_tuple[1:4]

5. Deleting a Tuple:

Once a tuple is created, you cannot change or delete its elements. However, you can delete the entire tuple.

del my_tuple

6. Tuple Methods:

Tuples have limited built-in methods. Two common methods are count() and index().

my_tuple = (1, 2, 2, 3, 4, 2)

count_of_2 = my_tuple.count(2)
index_of_3 = my_tuple.index(3)

7. Using Tuples as Keys in Dictionaries:

Tuples can be used as keys in dictionaries, for example, to represent coordinates.

coordinates_dict = { (1, 2): 'Point A', (3, 4): 'Point B' }

8. Immutable Nature:

Tuples are immutable, meaning their values cannot be changed after creation.

my_tuple = (1, 2, 3)
# This will raise an error
my_tuple[0] = 5

9. Nesting Tuples:

You can create a tuple of tuples.

nested_tuple = ((1, 2), (3, 4), (5, 6))

10. Using in and not in with Tuples:

 
my_tuple = (1, 2, 3, 'hello', 3.14)

if 3 in my_tuple:
    print("3 is in the tuple")
    
if 'world' not in my_tuple:
    print("'world' is not in the tuple")

Tuples are versatile data structures in Python, and understanding their properties and various operations can enhance your ability to work with them effectively.

Leave a Reply

Your email address will not be published. Required fields are marked *