Python provides several built-in data structures that help organize, store, and manipulate data efficiently. These are Lists, Tuples, Dictionaries, and Sets.
Lists
A list is an ordered, mutable (changeable) collection of elements. It allows duplicate values and can store different data types.
- Ordered (maintains insertion order)
- Mutable (can be modified)
- Allows duplicates
- Can store mixed data types
# Creating a list
my_list = [10, 20, 30, 40, 50]
# Accessing elements
print(my_list[0]) # First element
print(my_list[-1]) # Last element
# Modifying elements
my_list[1] = 25
# Adding elements
my_list.append(60)
# Removing elements
my_list.remove(30)
print(my_list)10
50
[10, 25, 40, 50, 60]List Operations
numbers = [1, 2, 3]
numbers.append(4) # Add at end
numbers.insert(1, 10) # Insert at index
numbers.pop() # Remove last
numbers.sort() # Sort list
print(numbers)[1, 2, 3, 10]Tuples
A tuple is an ordered, immutable collection of elements. Once created, it cannot be changed.
- Ordered
- Immutable (cannot modify)
- Allows duplicates
- Faster than lists (in many cases)
# Creating a tuple
my_tuple = (10, 20, 30, 40)
# Accessing elements
print(my_tuple[0])
print(my_tuple[-1])
# Tuple with mixed data types
mixed_tuple = (1, "Hello", 3.5)
print(mixed_tuple)10
40
(1, 'Hello', 3.5)Immutability
my_tuple = (1, 2, 3)
# This will cause an error
# my_tuple[0] = 10TypeError: 'tuple' object does not support item assignmentDictionaries
A dictionary stores data in key-value pairs. It is unordered (before Python 3.7), but now maintains insertion order.
- Key-value structure
- Keys must be unique
- Mutable
- Fast lookup using keys
# Creating a dictionary
student = {
"name": "Rahul",
"age": 21,
"course": "BCA"
}
# Accessing values
print(student["name"])
# Adding new key-value pair
student["marks"] = 85
# Updating value
student["age"] = 22
# Removing element
del student["course"]
print(student)Rahul
{'name': 'Rahul', 'age': 22, 'marks': 85}Dictionary Methods
data = {"a": 1, "b": 2}
print(data.keys())
print(data.values())
print(data.items())dict_keys(['a', 'b'])
dict_values([1, 2])
dict_items([('a', 1), ('b', 2)])Sets
A set is an unordered collection of unique elements. It does not allow duplicates.
- Mutable
- Useful for mathematical operations
# Creating a set
my_set = {1, 2, 3, 4}
# Adding elements
my_set.add(5)
# Removing elements
my_set.remove(2)
print(my_set){1, 3, 4, 5}Set Operations
A = {1, 2, 3}
B = {3, 4, 5}
print(A.union(B)) # Union
print(A.intersection(B)) # Intersection
print(A.difference(B)) # Difference{1, 2, 3, 4, 5}
{3}
{1, 2}Write a program to remove duplicates from a list
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)[1, 2, 3, 4, 5]🎉 Great progress! Jump to Learning Path ↑🐍 Try Quiz Game From This Lesson
Loading…
Score: 0
