Check out this video for an overview of the article. Then, read the article and solve exercises to strengthen your understanding.
1 Data Structures
Data structures are the ways to organize and store data in memory. They play a crucial role in computer science and programming as they determine how data can be accessed, manipulated, and stored efficiently. In this article, we will cover four basic data structures: lists, tuples, dictionaries, and sets.
1.1 List
A list is a type of data structure in “Python” programming that is used to store multiple items in a single variable. Lists are ordered, mutable, and can contain elements of different data types. You can access elements in a list using their index position.
TIPS
- ordered: The elements in a data structure, like a list or tuple, have a specific sequence and are stored in a specific order.
- mutable: The elements in a data structure can be changed after the structure is created.
Here is the example of a list:
# Creating a list of integers
numbers = [1, 2, 3, 4, 5]
print(numbers)
[1, 2, 3, 4, 5]
You can define a list by enclosing elements within square brackets []
. Each element is separated by a comma. The index in “Python” language starts from zero. This type of numbering way is called zero-based numbering. This means you can access the first element of the list with 0:
print(numbers[0]) # The first element of "numbers"
print(numbers[1]) # The second element of "numbers"
1
2
A list can store many types of objects:
# Creating a list of strings:
fruits = ["apple", "banana", "orange", "kiwi"]
print(fruits)
# Creating a list of mixed data types:
mixed_list = [1, "hello", 3.14, True]
print(mixed_list)
['apple', 'banana', 'orange', 'kiwi']
[1, 'hello', 3.14, True]
1.2 Tuple
A tuple is another data structure in “Python” programming. It is similar to a list, but with one key difference - tuples are immutable, meaning their elements cannot be changed once they are defined. Tuples are typically used to store a fixed sequence of elements.
Tuples in “Python” language are defined using parentheses ()
and can contain a sequence of elements:
# Creating a tuple of integers
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
(1, 2, 3, 4, 5)
As mentioned, tuples are immutable, meaning you can not edit the values in a tuple after creating it. On the other hand, lists are mutable:
# List is mutable.
# You can edit the elements in a list after creating it.
l = [1, 2, 3, 4]
print(l)
l[0] = 10 # Replace the first element with 10
print(l)
[1, 2, 3, 4]
[10, 2, 3, 4]
# Tuple is immutable.
# You can NOT edit the elements in a tuple after creating it.
t = (1, 2, 3, 4)
print(t)
# Don't care about try and except.
# These are just for handling the error.
try:
t[0] = 10 # This raises an error.
except TypeError as e:
print(e)
(1, 2, 3, 4)
'tuple' object does not support item assignment
1.3 Dictionary
A dictionary in “Python” language stores unique key-value pairs. Each key is used to access its corresponding value. Dictionaries are unordered and mutable. This means that you can not access the elements of it using indices but can edit the dictionary after the creation.
A dictionary is created with curly brackets {}
. A key and the corresponding value is separated by :
, and the pairs are separated by ,
.
# Creating a dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
In a dictionary my_dict
, name
is a key and John
is the corresponding value. You can access the value by specifying the key:
# Accessing values in a dictionary
print(my_dict['name']) # Output: John
print(my_dict.get('age')) # Output: 30
John
30
As you can see in the above code, there are two ways to access the value through a key. You can use either of them, but get()
is the safer way because it does not raise an error even the specified key does not exist in the dictionary:
try:
my_dict['NOTEXIST']
except KeyError as e:
print(f"Key does not exist: {e}")
Key does not exist: 'NOTEXIST'
print(my_dict.get('NOTEXIST'))
None
Because dictionaries are mutable, you can edit them:
print(f"Original: {my_dict}")
# Adding a new key-value pair
my_dict['gender'] = 'male'
print(f"Added gender: {my_dict}")
# Updating the value of a key
my_dict['age'] = 31
print(f"Changed age: {my_dict}")
# Removing a key-value pair
del my_dict['city']
print(f"Removed city: {my_dict}")
Original: {'name': 'John', 'age': 30, 'city': 'New York'}
Added gender: {'name': 'John', 'age': 30, 'city': 'New York', 'gender': 'male'}
Changed age: {'name': 'John', 'age': 31, 'city': 'New York', 'gender': 'male'}
Removed city: {'name': 'John', 'age': 31, 'gender': 'male'}
1.4 Set
A set is a collection of unique elements in “Python” language. Sets are unordered and mutable, meaning you can add or remove elements from a set. Sets are particularly useful for getting unique elements.
l = [1, 3, 9, 2, 1, 9, 1, 2, 6, 7] # List
print(l)
s = set(l) # Create a set
print(s)
new_l = list(s) # Convert to list
print(new_l)
[1, 3, 9, 2, 1, 9, 1, 2, 6, 7]
{1, 2, 3, 6, 7, 9}
[1, 2, 3, 6, 7, 9]
2 Exercise
Exercise 1 (1)
- Get the 25th element of the following list by specifying the index of the element.
- Then store the value to the variable
num_25
.
numbers = [1, 3, 5, 6, 7, 8, 10, 20, 21, 23, 24, 28, 29, 32, 33, 39, 41, 43, 50, 51, 57, 59, 60, 61, 62, 63, 66, 73, 74, 76, 78, 80, 81, 82, 84, 86, 91, 92, 93, 95, 96]
(2)
- Get the second element (dictionary) of
rectangles
. - Get the value of
base
of the above dictionary, and store it in a variablebase
. - Get the value of
height
of the above dictionary, and store it in a variableheight
. - Calculate the area of the rectangle using the above base and height.
- Store the area into the second element of
rectangles
. The key should bearea
. - Print
rectangles
and check ifarea
is correctly added.
rectangles = [{"base": 10, "height": 5}, {"base": 7, "height": 3}, {"base": 6, "height": 4}]
(3)
- Count the number of unique elements in
numbers
(Checklen()
function if needed). - Then store the value in the variable
num_numbers
.
numbers = [2, 0, 10, 8, 4, 3, 20, 10, 10, 20, 7, 18, 9, 13, 3, 6, 20, 19, 3, 4, 17, 5, 8, 8, 16, 9, 18, 10, 3, 6]
3 Answers
(1)
numbers = [1, 3, 5, 6, 7, 8, 10, 20, 21, 23, 24, 28, 29, 32, 33, 39, 41, 43, 50, 51, 57, 59, 60, 61, 62, 63, 66, 73, 74, 76, 78, 80, 81, 82, 84, 86, 91, 92, 93, 95, 96]
num_25 = numbers[24]
print(num_25)
62
(2)
rectangles = [{"base": 10, "height": 5}, {"base": 7, "height": 3}, {"base": 6, "height": 4}]
base = rectangles[1]["base"]
height = rectangles[1]["height"]
area = base * height
rectangles[1]["area"] = area
print(rectangles)
[{'base': 10, 'height': 5}, {'base': 7, 'height': 3, 'area': 21}, {'base': 6, 'height': 4}]
(3)
numbers = [2, 0, 10, 8, 4, 3, 20, 10, 10, 20, 7, 18, 9, 13, 3, 6, 20, 19, 3, 4, 17, 5, 8, 8, 16, 9, 18, 10, 3, 6]
num_numbers = len(set(numbers))
print(num_numbers)
print(set(numbers))
16
{0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 16, 17, 18, 19, 20}