Data structures in Python are containers that organize and store data. They are essential for writing efficient and optimized code. Python offers several built-in data structures, including lists, dictionaries, sets, and tuples. Each structure is designed to handle data in a specific way, making it suitable for different use cases.
Lists
A list in Python is an ordered, mutable collection of items. This means that the order of elements in the list is preserved, and you can modify the list by adding, removing, or changing items. Lists are versatile and can store different data types like integers, floats, strings, and even other lists.
Syntax:
list_name = [item1, item2, item3]
Examples:
cities = ["Manila", "Cebu", "Davao"] # List of strings numbers = [1, 2, 3, 4, 5] # List of integers mixed = [1, "Manila", 3.5, True] # List of mixed data types
Characteristics:
Ordered: Elemens in a list maintain the order in which they are added.
Mutable: You can change the list after it is created by adding, removing, or replacing items.
Dynamic: Lists can grow and shrink in size as needed.
Basic Methods:
# Adding an item to the end of the list cities.append("Makati") # cities -> ["Manila", "Cebu", "Davao", "Makati"]
# Removing an item by value cities.remove("Cebu") # cities → ["Manila", "Davao", "Makati"]
# Inserting an item at a specific index cities.insert(1, "Taguig") # cities → ["Manila", "Taguig", "Davao", "Makati"]
# Sorting the list in ascending order numbers.sort() # numbers → [1, 2, 3, 4, 5]
# Reversing the order of the list numbers.reverse() # numbers → [5, 4, 3, 2, 1]
# Getting the length of the list (number of items) length = len(cities) # length → 4
# Accessing elements using indexing first_city = cities[0] # first_city → "Manila"
Dictionary
A dictionary in Python is an unordered, mutable collection of key-value pairs. Each element in the dictionary consists of a unique key and an associated value. The key acts as an identifier for the value and must be an immutable data type (e.g., string, integer, or tuple). Values, on the other hand, can be any data type and can be accessed using their corresponding keys.
Syntax:
dict_name = {key1: value1, key2: value2}
Examples:
person = {"name": "Tala", "age": 22, "city": "Manila"}
Characteristics:
Unordered: Items in the dictionary do not have a defined order, but you access values using their unique keys.
Mutable: You can add, modify, or remove key-value pairs after the dictionary is created.
Key-Value Structure: Each entry has a key and a corresponding value, similar to a real-life dictionary with words and their meanings.
Basic Methods:
# Adding a key-value pair person["email"] = "tala@example.com" # person → {"name": "Tala", "age": 22, "city": "Manila", "email": "tala@example.com"}
# Removing a key-value pair del person["age"] # person→ {"name": "Tala", "city": "Manila", "email": "tala@example.com"}
# Accessing the value associated with a key name = person["name"] # name → "Tala"
# Getting all keys in the dictionary keys = person.keys() # keys → dict_keys(["name", "city", "email"])
# Getting all values in the dictionary values = person.values() # values → dict_values(["Tala", "Manila", "tala@example.com"])
# Checking if a key exists in the dictionary has_age = "age" in person # has_age → False
# Iterating through all key-value pairs for key, value in person.items(): print(key, value)
Set
A set in Python is an unordered collection of unique items. Sets do not allow duplicate elements, which makes them useful when you need to ensure that a collection contains only distinct values. Like dictionaries, sets are also mutable, meaning you can add or remove elements. However, the elements themselves must be immutable.
Syntax:
set_name = {item1, item2, item3}
Examples:
foods = {"adobo", "sinigang", "kare-kare"}
Characteristics:
- Unordered: The items have no specific order and cannot be accessed using an index.
- Unique Elements: No duplicate values are allowed.
- Mutable: You can add or remove items from the set.
Basic Methods:
# Adding an item to the set foods.add("sisig") # foods = {"adobo", "sinigang", "kare-kare", "sisig"}
# Removing an item from the set foods.remove("adobo") # foods = {"sinigang", "kare-kare", "sisig"}
# Checking if an item is in the set has_sisig = "sisig" in foods # has_sisig → True
# Getting the length of the set length = len(foods) # length → 3
# Set operations (union, intersection, difference) set1 = {1, 2, 3} set2 = {3, 4, 5} union = set1 | set2 # union -> {1, 2, 3, 4, 5} intersection = set1 & set2 # intersection -> {3} difference = set1 - set2 # difference -> {1, 2}
Tuple
A tuple in Python is an ordered, immutable collection of items. Tuples are similar to lists, but once a tuple is created, you cannot change, add, or remove items. Tuples are useful when you want to ensure that data remains constant throughout the program.
Syntax:
tuple_name = (item1, item2, item3)
Examples:
coordinates = (10.0, 20.0) person = ("Tala", 22, "Manila")
Characteristics:
Ordered: Like lists, the order of items in a tuple is preserved.
Immutable: Once created, the tuple cannot be modified in any way (no adding, removing, or changing items).
Heterogeneous: A tuple can contain elements of different data types.
Basic Methods:
# Accessing elements using indexing first_item = coordinates[0] # first_item → 10.0
# Getting the length of the tuple (number of items) length = len(person) # length → 3
# Tuples are immutable, so you cannot add, remove, or change items directly # However, you can concatenate tuples new_tuple = coordinates + (30.0,) # new_tuple → (10.0, 20.0, 30.0)