Tuple, Dictionarie, and Set
Tuple, Dictionarie, and Set
A data structure is a way of organizing and storing data efficiently. Apart from standard
types like strings and integers, Python provides tuples, dictionaries, and sets for
handling collections of data in different ways.
1. Tuples
Definition
• A tuple is an ordered, immutable collection of elements.
• Elements in a tuple cannot be modified after creation.
• Tuples can store multiple data types.
• Tuples use parentheses () or can be defined without them (Tuple
Packing).
Creating a Tuple
a = (1, 2)
b = "eat", "dinner", "man", "boy" # Tuple Packing
print(a) # Output: (1, 2)
print(type(a)) # Output: <class 'tuple'>
Empty Tuple
empty_tuple = ()
print(type(empty_tuple)) # Output: <class 'tuple'>
a = ("Hamburger",) # Correct
print(type(a)) # Output: <class 'tuple'>
b = ("Hamburger") # Incorrect
print(type(b)) # Output: <class 'str'>
Tuple vs List
Accessing Elements
• Indexing (0-based)
• Negative Indexing (Last element is -1)
Slicing
Operations on Tuples
• Concatenation
a = (1, 2, 3)
b = (4, 5, 6)
print(a + b) # Output: (1, 2, 3, 4, 5, 6)
Repetition
Finding Min/Max
print(min(a)) # Output: 1
print(max(a)) # Output: 3
myList = [1, 2, 3, 4]
myTuple = tuple(myList)
print(myTuple) # Output: (1, 2, 3, 4)
Tuple in Functions
printNums(1, 2, 3, 4, 5)
# Output: 1, 2, (3, 4, 5)
2. Dictionaries
Definition
• A dictionary is an unordered collection of key-value pairs.
• Keys are unique and immutable (e.g., strings, numbers, tuples).
• Values can be mutable or immutable.
• Uses curly brackets {}.
Creating a Dictionary
Accessing Elements
Adding/Updating Elements
Removing Elements
Dictionary Methods
• Get All Keys
• Get All Keys
Merging Dictionaries
3. Sets
Definition
• A set is an unordered collection of unique elements.
• No duplicate values are allowed.
• Mutable (you can add/remove elements), but elements inside must be
immutable.
• Uses curly brackets {} or set() function.
Creating a Set
Set Operations
Union (|)
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # Output: {1, 2, 3, 4, 5}
Intersection (&)
Difference (-)