Data Structures in Python
1. Lists
A list is an ordered, mutable collection of items. Lists can contain elements
of different data types.
Creating Lists:
# Creating a list
my_list = [1, 2, 3, 4, 5]
mixed_list = [1, "Hello", 3.14, True]
Accessing Elements:
Use indexing to access elements (starting from 0).
print(my_list[0]) # Output: 1
Common List Operations:
# Adding elements
my_list.append(6) # Adds 6 to the end
my_list.insert(2, "Hi") # Inserts "Hi" at index 2
# Removing elements
my_list.remove(3) # Removes the first occurrence of 3
my_list.pop() # Removes the last element
# Slicing
sub_list = my_list[1:4] # Gets elements from index 1 to 3
# Sorting
my_list.sort() # Sorts the list in ascending order
my_list.reverse() # Reverses the order of elements
, 2. Tuples
A tuple is an ordered, immutable collection of items. Once created, the
elements cannot be changed.
Creating Tuples:
my_tuple = (1, 2, 3)
single_element_tuple = (5,) # Comma is required for single-element tuples
Accessing Elements:
print(my_tuple[1]) # Output: 2
Use Cases:
Tuples are used when you want to ensure data cannot be changed, such as
storing coordinates.
3. Dictionaries
A dictionary is an unordered collection of key-value pairs. Keys must be
unique and immutable (e.g., strings, numbers, tuples).
Creating Dictionaries:
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
Accessing Elements:
print(my_dict["name"]) # Output: Alice
1. Lists
A list is an ordered, mutable collection of items. Lists can contain elements
of different data types.
Creating Lists:
# Creating a list
my_list = [1, 2, 3, 4, 5]
mixed_list = [1, "Hello", 3.14, True]
Accessing Elements:
Use indexing to access elements (starting from 0).
print(my_list[0]) # Output: 1
Common List Operations:
# Adding elements
my_list.append(6) # Adds 6 to the end
my_list.insert(2, "Hi") # Inserts "Hi" at index 2
# Removing elements
my_list.remove(3) # Removes the first occurrence of 3
my_list.pop() # Removes the last element
# Slicing
sub_list = my_list[1:4] # Gets elements from index 1 to 3
# Sorting
my_list.sort() # Sorts the list in ascending order
my_list.reverse() # Reverses the order of elements
, 2. Tuples
A tuple is an ordered, immutable collection of items. Once created, the
elements cannot be changed.
Creating Tuples:
my_tuple = (1, 2, 3)
single_element_tuple = (5,) # Comma is required for single-element tuples
Accessing Elements:
print(my_tuple[1]) # Output: 2
Use Cases:
Tuples are used when you want to ensure data cannot be changed, such as
storing coordinates.
3. Dictionaries
A dictionary is an unordered collection of key-value pairs. Keys must be
unique and immutable (e.g., strings, numbers, tuples).
Creating Dictionaries:
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
Accessing Elements:
print(my_dict["name"]) # Output: Alice