12.Python Core Data Structures & Functions

 Tuples & Sets Deep Dive

Tuples and Sets are two fundamental data structures in Python. They serve different purposes: Tuples are ordered and immutable sequences, while Sets are unordered collections of unique elements. Understanding these structures is essential for writing efficient and clean Python code.

Tuples in Python

A tuple is an immutable sequence type. Once created, its elements cannot be changed, added, or removed. Tuples are commonly used for fixed collections of items, such as coordinates or configuration values.

Syntax and Examples:

Creating tuples:

my_tuple = (1, 2, 3)
empty_tuple = ()
single_element_tuple = (5,)  # Note the comma

Accessing elements:

print(my_tuple[0])  # Output: 1
print(my_tuple[-1])  # Output: 3

Tuple unpacking:

a, b, c = my_tuple
print(a, b, c)  # Output: 1 2 3

Common Tuple Methods:

Method

Description

count(x)

Returns the number of times x appears in the tuple

index(x)

Returns the index of the first occurrence of x

Sets in Python

A set is an unordered collection of unique elements. Sets are useful for membership tests, removing duplicates, and performing mathematical set operations like union and intersection.

Syntax and Examples:

Creating sets:

my_set = {1, 2, 3}
empty_set = set()

Adding and removing elements:

my_set.add(4)
my_set.remove(2)

Common Set Methods:

Method

Description

add(x)

Adds element x to the set

remove(x)

Removes element x from the set; raises error if not found

discard(x)

Removes element x if present; no error if not found

union(s)

Returns a new set with elements from both sets

intersection(s)

Returns a new set with common elements

difference(s)

Returns a new set with elements in the first set but not in s

Advanced Features and Best Practices

 

Tuples:
– Use tuples for fixed collections of items.
– Tuples can be used as dictionary keys because they are immutable.
– Prefer tuples over lists when immutability is desired for safety and performance.

Sets:
– Use sets to eliminate duplicates from a sequence.
– Set operations (union, intersection, difference) are efficient for large collections.
– Avoid relying on element order in sets since they are unordered.

Scroll to Top
Tutorialsjet.com