Data Structures in Python: Overview and Implementation
Python is a high-level, interpreted programming language that is widely used in various domains, such as data science, web development, artificial intelligence and automation. One of the strengths of Python is its rich set of data structures, which make it easier to handle and manipulate complex data.
Python provides built-in support for several data structures, including lists, tuples, dictionaries, sets. Each data structure has its own characteristics and is suitable for specific use cases. By choosing the appropriate data structure for a specific task, you can improve the performance of your code and make it more readable and maintainable. Data structures are important because they allow us to organize data in a way that makes it easy to access, store and manipulate.
Python Built-in Data Structures
List
List is a built-in data structure that allows you to store a collection of items of different data types, such as numbers, strings or other lists. Lists are mutable, which means you can modify their contents by adding, removing, or changing items.
Creating a list
cars = ["Porsche", "Mclaren", "Bugatti"]
print(cars)
Access items from list
List items are indexed and you can access them by referring to the index number
cars = ["Porsche", "Mclaren", "Bugatti"]
print(cars[1])
Accessing Item by using Indexing
- Using Negative Indexing: Negative indexing means start from the end.
cars = ["Porsche", "Mclaren", "Bugatti"]
print(cars[-1])
- Using Range of Index: You can specify a range of indexes by specifying where to start and where to end the range.
cars = ["Porsche", "Mclaren", "Bugatti", "Mercedes", "Lamborghini"]
print(cars[1:3])
cars = ["Porsche", "Mclaren", "Bugatti", "Mercedes", "Lamborghini"]
print(cars[1:])
cars = ["Porsche", "Mclaren", "Bugatti", "Mercedes", "Lamborghini"]
print(cars[:3])
Changing or Updating items of list
cars = ["Porsche", "Mclaren", "Bugatti", "Mercedes", "Lamborghini"]
cars[3] = "Ferrari"
print(cars)
- Change via Range of Item Values: To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values:
cars = ["Porsche", "Mclaren", "Bugatti", "Mercedes", "Lamborghini"]
cars[3:4] = ["Ferrari","Koenigsegg"]
print(cars)
- Insert Items to list: To insert a new list item, without replacing any of the existing values, we can use the
insert()
method.
cars = ["Porsche", "Mclaren", "Bugatti", "Mercedes", "Lamborghini"]
cars.insert(3, "Ferrari")
print(cars)
Adding new items to list
To add an item to the end of the list, use the append() method:
cars = ["Porsche", "Mclaren", "Bugatti"]
cars.append("Bently")
print(cars)
- Inserting Items to list
cars = ["Porsche", "Mclaren", "Bugatti"]
cars.insert(2, "Bently")
print(cars)
Extending lists items
cars = ["Porsche", "Mclaren", "Bugatti"]
models = ["GT3", "765LT", "Chiron"]
cars.extend(models)
print(cars)
Remove items from the list
The remove()
method removes the specified item.
cars = ["Porsche", "Mclaren", "Bugatti"]
cars.remove("Mclaren")
print(cars)
- Remove the specified index
cars = ["Porsche", "Mclaren", "Bugatti"]
cars.pop(1)
print(cars)
If you do not specify the index, the pop()
method removes the last item.
Looping List
You can loop through the list items by using a for
loop:
cars = ["Porsche", "Mclaren", "Bugatti"]
for i in cars:
print(i)
- Loop Through the Index: You can also loop through the list items by referring to their index number. Use the
range()
andlen()
functions to create a suitable iterable.
cars = ["Porsche", "Mclaren", "Bugatti"]
for i in range(len(cars)):
print(cars[i])
Sorting list
List objects have a sort()
method that will sort the list alphanumerically, ascending, by default:
cars = ["Porsche", "Mclaren", "Bugatti"]
cars.sort()
print(cars)
- Sort by descending order: To sort descending, use the keyword argument
reverse = True
cars = ["Porsche", "Mclaren", "Bugatti"]
cars.sort(reverse=True)
print(cars)
list1 = [100, 50, 65, 82, 23]
list1.sort(reverse = True)
print(list1)
Joining lists
One of the easiest ways are by using the +
operator.
cars = ["Porsche", "Mclaren", "Bugatti"]
models = ["GT3", "765LT", "Chiron"]
new_list = cars + models
print(new_list)
You can use the extend()
method, which purpose is to add elements from one list to another list:
cars = ["Porsche", "Mclaren", "Bugatti"]
models = ["GT3", "765LT", "Chiron"]
cars.extend(models)
print(cars)
Lists Methods
Tuples
Tuple is a built-in data structure that is similar to a list, but it is immutable, which means you cannot change its contents once it is created. Tuples are typically used to store a sequence of related values that should not be modified.
Creating a tuple
cars = ("Porsche", "Mclaren", "Bugatti")
print(cars)
Accessing items from tuple
You can access tuple items by referring to the index number, inside square brackets:
cars = ("Porsche", "Mclaren", "Bugatti")
print(cars[1])
Accessing Item by using Indexing
- Using Negative Indexing: Negative indexing means start from the end
cars = ("Porsche", "Mclaren", "Bugatti")
print(cars[-1])
- Using Range of Index: You can specify a range of indexes by specifying where to start and where to end the range.
cars = ("Porsche", "Mclaren", "Bugatti", "Mercedes", "Lamborghini")
print(cars[1:3])
cars = ("Porsche", "Mclaren", "Bugatti", "Mercedes", "Lamborghini")
print(cars[1:])
cars = ("Porsche", "Mclaren", "Bugatti", "Mercedes", "Lamborghini")
print(cars[:3])
Adding new items to Tuple
Once a tuple is created, you cannot change its values. Tuples are unchangeable or immutable. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
cars = ("Porsche", "Mclaren", "Bugatti")
x = list(cars)
x.append("Ferrari")
cars = tuple(x)
print(cars)
cars = ("Porsche", "Mclaren", "Bugatti")
x = list(cars)
x[1] = "Ferrari"
cars = tuple(x)
print(cars)
Looping Tuple
You can loop through the list items by using a for
loop:
cars = ("Porsche", "Mclaren", "Bugatti")
for i in cars:
print(i)
- Loop Through the Index Numbers: You can also loop through the list items by referring to their index number. Use the
range()
andlen()
functions to create a suitable iterable.
cars = ("Porsche", "Mclaren", "Bugatti")
for i in range(len(cars)):
print(cars[i])
Joining Tuples
One of the easiest ways are by using the +
operator:
cars = ("Porsche", "Mclaren", "Bugatti")
models = ("GT3", "765LT", "Chiron")
new_list = cars + models
print(new_list)
Sets
Set is an unordered collection of unique elements. This means that a set cannot contain duplicate values. The elements of a set can be of any data type, including numbers, strings, and other objects.
Creating a Set
cars = {"Porsche", "Mclaren", "Bugatti"}
print(cars)
Accessing items in Set
You cannot access items in a set by referring to an index or a key. But you can loop through the set items using a for
loop, or ask if a specified value is present in a set, by using the in
keyword.
# Using FOR Loop
cars = {"Porsche", "Mclaren", "Bugatti"}
for i in cars:
print(i)
#Using IN keyword
cars = {"Porsche", "Mclaren", "Bugatti"}
print("Porsche" in cars)
Adding elements to Set
To add one item to a set use the add()
method.
cars = {"Porsche", "Mclaren", "Bugatti"}
cars.add("Dodge")
print(cars)
- Adding items to set : To add items from another set into the current set, use the
update()
method.
cars = {"Porsche", "Mclaren", "Bugatti"}
models = {"GT3", "720s", "Chiron"}
cars.update(models)
print(cars)
Removing any item from Set
To remove an item in a set, use the remove()
cars = {"Porsche", "Mclaren", "Bugatti"}
cars.remove("Bugatti")
print(cars)
or the discard()
method.
cars = {"Porsche", "Mclaren", "Bugatti"}
cars.discard("Bugatti")
print(cars)
Looping Sets
You can loop through the set items by using a for
loop:
cars = {"Porsche", "Mclaren", "Bugatti"}
for i in cars:
print(i)
Joining Set
- Using Union: You can use the
union()
method that returns a new set containing all items from both sets
cars = {"Porsche", "Mclaren", "Bugatti"}
models = {"GT3", "720s", "Chiron"}
cars.union(models)
print(cars)
or the update()
method that inserts all the items from one set into another
cars = {"Porsche", "Mclaren", "Bugatti"}
models = {"GT3", "720s", "Chiron"}
cars.update(models)
print(cars)
- Using Intersection:
intersection()
method will return a new set, that only contains the items that are present in both sets.
cars = {"Porsche", "Mclaren", "Bugatti"}
models = {"GT3", "720s", "Chiron"}
cars.intersection(models)
print(cars)
Dictionary
Dictionary (or “dict” for short) is a built-in data structure that allows you to store a collection of key-value pairs. Each key in a dictionary is unique, and it is used to access the corresponding value.
Creating a Dictionary
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
print(car)
Accessing items from Dictionary
- Get Keys: The
keys()
method will return a list of all the keys in the dictionary.
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
x = car.keys()
print(x)
- Get Values: The
values()
method will return a list of all the values in the dictionary.
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
x = car.values()
print(x)
- Get Items: The
items()
method will return each item in a dictionary, as tuples in a list.
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
x = car.items()
print(x)
Changing Items
- Change Values: You can change the value of a specific item by referring to its key name
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
car["model"] = "765LT"
- Updating: The
update()
method will update the dictionary with the items from the given argument.
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
car.update({"year": 2021})
Adding items to Dictionary
The update()
method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
car.update({"year": 2021}
You can add the value of a specific item by referring to its key name
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
car["model"] = "765LT"
Removing Items
The pop()
method removes the item with the specified key name
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
car.pop("year")
print(car)
The del
keyword removes the item with the specified key name
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
del car["year"]
print(car)
Looping Dictionary
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
for i in car:
print(i)
- Using
values()
method to return values of a dictionary:
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
for i in car.values():
print(i)
- Using
keys()
method to return the keys of a dictionary:
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
for i in car.keys():
print(i)
- Using both keys and values, by using the
items()
method:
car = {
"name" : "mclaren",
"model" : "720s",
"year" : 2020
}
for x, y in car.items():
print(x, y)
Summary
Python provides several built-in data structures that are useful for organizing and manipulating data. These include:
- Lists: Lists are ordered collections of elements that can be of any data type. They are mutable, meaning that you can add, remove or modify elements in a list.
- Tuples: Tuples are similar to lists, but they are immutable, meaning that once you create a tuple, you cannot change its contents.
- Sets: Sets are unordered collections of unique elements. They are useful for performing set operations such as union and intersection
- Dictionaries: Dictionaries are collections of key-value pairs. Each key is unique and is used to access the corresponding value.