Tuples in python
Tuples in python
Tuples
A tuple in Python is a built-in data structure that allows you to store a collection of items. Tuples
are similar to lists but have some key differences that make them unique. Here’s a detailed
overview of the tuple data structure in Python:
Characteristics of Tuples
1. Immutable:
o Once a tuple is created, its contents cannot be changed (i.e., you cannot add,
remove, or modify elements).
2. Ordered:
o Tuples maintain the order of elements, meaning that the position of each element
is fixed.
3. Allow Duplicates:
o Tuples can contain duplicate values, just like lists.
4. Heterogeneous:
o A tuple can hold items of different data types, including integers, strings, lists,
and even other tuples.
1. Immutable: Once created, the contents of a tuple cannot be changed (no addition,
deletion, or modification of elements).
2. Ordered: Tuples maintain the order of elements, which means the position of each
element is fixed.
3. Allow Duplicates: Tuples can contain multiple occurrences of the same value.
4. Heterogeneous: A tuple can store items of different data types, such as integers, strings,
and lists.
5. Indexable: Elements can be accessed using zero-based indexing.
6. Lightweight: Tuples are generally more memory-efficient than lists.
Syntax of Tuples
Tuples are created by placing a comma-separated sequence of items inside parentheses ().
# Basic syntax
my_tuple = (item1, item2, item3)
Examples
1. Creating a Tuple
# Creating a tuple with integers
tuple_of_numbers = (1, 2, 3, 4, 5)
print(tuple_of_numbers) # Output: (1, 2, 3, 4, 5)
# Creating a tuple with mixed data types
mixed_tuple = (1, "Hello", 3.14, True)
print(mixed_tuple) # Output: (1, 'Hello', 3.14, True)
• Concatenation:
tuple1 = (1, 2)
tuple2 = (3, 4)
combined = tuple1 + tuple2
print(combined) # Output: (1, 2, 3, 4)
• Repetition:
repeated = tuple1 * 3
print(repeated) # Output: (1, 2, 1, 2, 1, 2)
• Membership Test:
• Count:
my_tuple = (1, 2, 2, 3)
print(my_tuple.count(2)) # Output: 2
• Index:
print(my_tuple.index(2)) # Output: 1
5. Packing and Unpacking
• Packing:
• Unpacking:
a, b, c = packed_tuple
print(a, b, c) # Output: 1 2 3