Introduction
In this lab, we'll learn data structures in Python, the main contents of the data structures we'll be working with are: lists, tuples, dictionaries, and sets.
Achievements
- Lists
- List Comprehensions
- Tuples
- Dictionaries
- Sets
In this lab, we'll learn data structures in Python, the main contents of the data structures we'll be working with are: lists, tuples, dictionaries, and sets.
In Python, lists serve as versatile containers capable of holding various types of objects. Here, we'll explore fundamental list operations such as creation, accessing values, updating values, appending values, and deleting values.
Lists are defined with comma-separated values enclosed in square brackets. Data items in a list do not need to be of the same type.
>>> l1 = [1, 2, 3, 'a', 'hello']
>>> l1
[1, 2, 3, 'a', 'hello']
>>> l2 = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
>>> l2
['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
Use the subscript index to access the values in the list.
>>> print("l1[0] = ", l1[0])
l1[0] = 1
You can use the square bracketed form to intercept characters as follows, which is called a slice. Slice is a way of extracting a range of items from a list.
list_name[Start:End:Step]
The first index (Start) is the start index and the second index (End) is the end index. The third index (Step) is the step, where step is the increment (default 1).
>>> print("l2[1:3] = ", l2[1:3])
l2[1:3] = ['tuesday', 'wednesday']
You can update the value by using the subscript index to access the value, and then assign a new value to it:
>>> l1[0] = 10
>>> l1
[10, 2, 3, 'a', 'hello']
You can append values to the list by using the append()
method.
list_name.append(value)
>>> l1.append('b')
>>> l1
[10, 2, 3, 'a', 'hello', 'b']
>>> l2.append('statuday')
>>> l2
['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'statuday']
You can delete values from the list by using the del
keyword, this method deletes the element at the specified index from the list.
del list_name[index]
>>> del l1[0]
>>> l1
[2, 3, 'a', 'hello', 'b']
And you can also use the remove()
method to delete the specified value from the list.
list_name.remove(value)
>>> l1.remove('a')
>>> l1
[2, 3, 'hello', 'b']
You can use the len()
function to get the length of a list.
>>> print("Length of l1 = ", len(l1))
Length of l1 = 5
And the sorted()
function to sort the list.
>>> print("Sorted of l2 = ", sorted(l2))
Sorted of l2 = ['friday', 'monday', 'thursday', 'tuesday', 'wednesday']
List comprehension is a concise and powerful way of creating lists in Python by iterating over an existing iterable, such as a list, and applying an expression to each item to create a new list.
The format of a list comprehension can be understood as a for
loop. And the syntax of a list comprehension is:
new_list = [expression for item in old_list]
new_list = [expression for item in old_list if condition]
new_list
: The resulting list generated from the expression for each item in the old list.expression
: The operation or transformation applied to each item from the old list to generate the new list.item
: The variable representing each item in the old list.old_list
: The existing list used to generate the new list.condition
(optional): A filter condition that can be applied to include only certain items from the old list based on a specified criterion.Let's practice list comprehension in the Python shell:
>>> ls = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> even_list = [item for item in ls if item % 2 == 0]
>>> even_list
[2, 4, 6, 8, 10]
In this example, even_list will contain only the even numbers from the list ls.
List comprehensions provide a concise and readable way to manipulate lists, making Python code more expressive and efficient.
Tuples are similar to lists in Python, except that the elements of a tuple are immutable, meaning they cannot be changed after creation. Elements of tuples are enclosed within ()
and separated by ,
.
Create a tuple with the following elements:
>>> tup1 = ('Google', 'Run', 'Python')
>>> tup2 = (1, 2, 3, 4, 5)
>>> empty_tup = ()
>>> tup1
('Google', 'Run', 'Python')
>>> tup2
(1, 2, 3, 4, 5)
>>> empty_tup
()
Access elements of tuples using indexing:
>>> print(tup1[0])
Google
>>> print(tup2[1:3])
(2, 3)
>>> print(empty_tup[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range ## Error occurs, because tuple is empty.
While tuples cannot be modified, they can be merged:
>>> tup3 = tup1 + tup2
>>> print(tup3)
('Google', 'Run', 'Python', 1, 2, 3, 4, 5)
Tuples offer a reliable way to store data that should not be modified, providing stability and integrity to your Python programs.
Dictionaries in Python are versatile and mutable data structures that store key-value pairs.
Each key-value pair is separated by a colon, and each pair is separated by a comma, with the entire dictionary enclosed in curly braces {}
.
d = {key1 : value1, key2 : value2, key3 : value3 }
Keys in a dictionary must be unique, but values can be duplicated.
Create dictionaries with key-value pairs:
>>> dict1 = {'name': 'James', "age": 23, "phone": "12345"}
>>> dict2 = {}
>>> dict1
{'name': 'James', 'age': 23, 'phone': '12345'}
>>> dict2
{}
Access key-value pairs using the key within square brackets []
or the get()
function:
>>> print(dict1["name"])
James
>>> print(dict2["name"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'name'
>>> print(dict2.get("name"))
None
Using dict[key]
to access a key that does not exist in the dictionary raises a KeyError exception. However, dict.get(key)
returns None
if the key is not found in the dictionary.
Add or modify entries in a dictionary by assigning values to keys:
>>> dict2["name"] = "Lily"
>>> dict1["name"] = "Bob"
>>> dict2["name"]
'Lily'
>>> dict1["name"]
'Bob'
Delete key-value pairs using del dict[key]
or clear the entire dictionary using dict.clear()
:
>>> del dict1["name"]
>>> print(dict1)
{'age': 23, 'phone': '12345'}
>>> dict2.clear()
>>> print(dict2)
{}
Dictionaries offer a flexible way to store and manipulate data, making them essential for various tasks in Python programming.
Sets in Python are unordered collections of unique elements. They can be created using curly braces {}
or the set()
function.
To create an empty set, you must use set()
instead of {}
, as {}
is used to create an empty dictionary. Create sets using different methods:
>>> set1 = set()
>>> print(set1)
set()
>>> set2 = {'apple', 'orange', 'banana'}
>>> print(set2)
{'banana', 'apple', 'orange'}
>>> set3 = set("Hello World!")
>>> print(set3)
{'o', 'H', 'W', ' ', 'd', 'r', '!', 'e', 'l'}
Add elements to a set using the add()
or update()
methods:
>>> set1.add('apple')
>>> print(set1)
{'apple'}
>>> set2.update({'orange', 'pear'})
>>> print(set2)
{'apple', 'orange', 'banana', 'pear'}
Remove elements from a set using the discard()
or remove()
methods.
The discard()
method doesn't raise an error if the element is not present in the set, while the remove()
method does.
>>> set1.remove('apple')
>>> print(set1)
set()
>>> set1.discard('banana')
>>> print(set1)
set()
Sets provide a convenient way to work with collections of unique elements in Python, making them useful for various tasks such as removing duplicates or testing for membership.
Congratulations! You have completed the data structures Lab.
In this lab, you have learnt Python's basic data structures and When and how to use these data structures in solving problems.