Data structures are used for storing and organizing data efficiently. They allow you to quickly access and manipulate the data. Python includes many built-in data structures that enable easy data management. In this article, we will learn about two of Python’s most important data structures, lists & tuples.
The most flexible data structure in Python is a list. They are used to store a variety of data items, ranging from integers to strings and even another list! They are mutable, meaning their elements can be changed even after the list has been created.
Lists are formed by enclosing elements within [square] brackets and separating each item with a comma.
1 2 3 4
#creating a list test_list = ['Engineer', 'Doctor', 'Architect'] print(type(test_list)) print(test_list)
output:
1
< class 'list' > ['Engineer', 'Doctor', 'Architect']
Indexing is used to access list elements. Each list element has an index corresponding to its position in the list. The first item on the list has an index of 0, the second has an index of 1, and so on. The list’s final element has an index that is one less than the list’s length.
1
2
3
4
5
#creating a list
test_list = ['Engineer', 'Doctor', 'Architect']
print(test_list[0])
print(test_list[1])
print(test_list[2])
output:
1 2 3
Engineer Doctor Architect
There are a few unique features in the list data structure.
We can have duplicate values in the list since each element has its position, and using that, we can access the element.
1
2
3
4
#creating a list with duplicate values
test_list = ['Engineer', 'Doctor', 'Architect', 'Doctor']
print(test_list[1])
print(test_list[3])
output:
1 2
Doctor Doctor
We can have different types of values in the same list.
1
2
3
4
5
#creating a list with different types of values
test_list = ['Engineer', 10, 10.5, 'Doctor', -1]
print(test_list[1])
print(test_list[2])
print(test_list[4])
output:
1
2
3
4
10
10.5
-
1
In the list, we can access the elements using negative indexes.
1
2
3
4
5
6
7
#accessing the list with negative indexes
test_list = ['Engineer', 'lawyer', 'Architect', 'Doctor', ' Accountant']
print(test_list[-1]) # it will print last element in the list
print(test_list[-2]) # it will print second last element in the list
print(test_list[-3]) # it will print third last element in the list
print(test_list[-4]) # it will print fourth last element in the list
print(test_list[-5]) # it will print fifth last element in the list
output:
1 2 3 4 5
Accountant Doctor Architect lawyer Engineer
We can return the range of elements between two positions in the list. This concept is called slicing. To return the elements in the range, we need to supply the start and end indexes like this List_name[start : end]. This will print the elements between including the start index and excluding the end index.
1
2
3
4
5
#accessing the list to
return the range of elements
test_list = ['Engineer', 'lawyer', 'Architect', 'Doctor', ' Accountant']
print(test_list[1: 3])
print(test_list[2: 4])
output:
1 2
['lawyer', 'Architect'] ['Architect', 'Doctor', ' Accountant']
We can add new members to an existing list using the append()
or insert()
methods.
append()
This operation will add the particular element to the last position.
1 2 3 4
#appending the elements to the list test_list = ['Engineer', 'lawyer', 'Architect', 'Doctor', 'Accountant'] test_list.append('Designer') print(test_list)
output:
1
['Engineer', 'lawyer', 'Architect', 'Doctor', 'Accountant', 'Designer']
insert()
This operation will insert the particular element to the specified position.
1
2
3
4
#inserting the elements to the list
test_list = ['Engineer', 'lawyer', 'Architect', 'Doctor', 'Accountant']
test_list.insert(1, 'Designer')
print(test_list)
output:
1
['Engineer', 'Designer', 'lawyer', 'Architect', 'Doctor', 'Accountant']
Using the remove()
or pop()
methods, we can remove elements from a list just like adding them using append()
or insert()
.
remove()
This operation will remove the first occurrence from the list that matches a specified value.
1 2 3 4
#removing the elements from the list test_list = ['Engineer', 'Designer', 'lawyer', 'Architect', 'Doctor', 'Accountant'] test_list.remove('Designer') print(test_list)
output:
1
['Engineer', 'lawyer', 'Architect', 'Doctor', 'Accountant']
pop()
This operation will remove an element at a specified index from the list. If no index is specified, then the last element will be removed.
1
2
3
4
#removing the element at the particular index from the list
test_list = ['Engineer', 'Designer', 'lawyer', 'Architect', 'Doctor', 'Accountant']
test_list.pop(3)
print(test_list)
output:
1
['Engineer', 'Designer', 'lawyer', 'Doctor', 'Accountant']
Sorting is an important operation in data structures, and we will be using this operation most of the time. In Python, we can use the sort() function and it will allow you to reorder your list either in ascending or descending order.
1
2
3
4
5
6
#sorting ascending & descending
prime_numbers = [5, 7, 2, 13, 11, 3, 17]
prime_numbers.sort()
print(prime_numbers)
prime_numbers.sort(reverse = True)
print(prime_numbers)
output:
1
2
[2, 3, 5, 7, 11, 13, 17]
[17, 13, 11, 7, 5, 3, 2]
But this is not a straightforward thing when it comes to sorting the list which has string values. These string elements are stored as ASCII values. Each character in the string has an integer value associated with it and with that we use these values to sort the strings.
1 2 3 4 5
test_list = ['Engineer', 'Designer', 'Lawyer', 'Architect', 'Doctor', 'Accountant'] test_list.sort() print(test_list) test_list.sort(reverse = True) print(test_list)
output:
1 2
['Accountant', 'Architect', 'Designer', 'Doctor', 'Engineer', 'Lawyer'] ['Lawyer', 'Engineer', 'Doctor', 'Designer', 'Architect', 'Accountant']
Two or more lists can be concatenated using the ‘+’ symbol. This will return a single list with two or more lists combined.
1 2 3 4 5
#concatenating two lists test_list1 = ['Engineer', 'Designer', 'Lawyer'] test_list2 = ['Architect', 'Doctor', 'Accountant'] test_list = test_list1 + test_list2 print(test_list)
output:
1
['Engineer', 'Designer', 'Lawyer', 'Architect', 'Doctor', 'Accountant']
List comprehension offers a convenient method of producing new lists. By performing an operation on each element of an existing list, these new lists are generated.
1
2
3
4
5
num = [1, 2, 3, 4]
cube = []
for x in num:
cube.append(x ** 3)
print(cube)
output:
1
[1, 8, 27, 64]
The above traditional for-loop can be concisely written into a single line of code using list comprehensions.
1
2
3
4
num = [1, 2, 3, 4]
cube = [x ** 3
for x in num]
print(cube)
output:
1
[1, 8, 27, 64]
Python comes with a built-in data structure called a list. However, we can employ it to produce custom data structures. Stacks and queues are two extremely well-liked user-defined data structures created using lists.
Stacks are lists of elements where new elements are added at the start of the list or removed at the end of the list. Imagine it as a pile of books. You always work your way up the stack whenever you need to add or remove a book. It employs the straightforward Last-In-First-Out principle.
1
2
3
4
5
stack = [1, 2, 3, 4]
stack.append(5)
print(stack)
stack.pop()
print(stack)
output:
1
2
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
On the other hand, a queue is a list of elements in which new elements are added to the end of the list and old elements are removed from the front of the list. It is comparable to standing in a line in the real world. The line gets shorter as those at the front of the line leave. It gets longer when a new person joins the queue from the back. It takes advantage of the First-In-First-Out principle.
1
2
3
4
5
queue = [1, 2, 3, 4]
queue.append(5)
print(queue)
queue.pop(0)
print(queue)
output:
1
2
[1, 2, 3, 4, 5]
[2, 3, 4, 5]
Another well-liked built-in data structure in Python is the tuple. These are quite similar to lists with one exception - their immutability.
This implies that a tuple cannot be modified or added to after it has been formed. Let’s see how to create a tuple in Python and how to play with it below.
You can create tuples by enclosing data in parenthesis and separating each piece with a comma. You can create a tuple even if you write a number of items in a row without any parenthesis and assign them to a variable.
1
2
3
4
5
6
7
8
9
10
11
12
country = ('india', 'canada', 'u.s.a')
print(type(country))
print(country)
currency = (85, 'inr', 'usd', 'cad')
print(type(currency))
print(currency)
<
class 'tuple' >
('india', 'canada', 'u.s.a') <
class 'tuple' >
(85, 'inr', 'usd', 'cad')
Now that we have created tuples let’s see about their immutable nature.
Immutable in Python refers to something that cannot be changed after creation. The two types of objects in the Python programming language are mutable and immutable.
Lists, dictionaries, and sets are examples of mutable objects which can be altered after creation. We shall explore these in the following sections. In contrast, immutable objects include integers, floating-point numbers, boolean values, strings, and tuples. What, then, makes them unchangeable?
Everything in Python is an object. As a result, we may check an object’s memory address using the built-in id() method. This is known as the identity of the object. Let’s make a list then locate the list and all of its components.
1
2
3
thislist = ["apple", "banana", "cherry"]
print(id(thislist))
print(id(thislist[0]))
output:
1
2
47251449707712
47251450601840
You can see that the list and its elements are stored in different parts of memory. We can change the value of a list’s elements since we know that lists are mutable. Let’s try that and watch how the location values change.
1
2
3
thislist[0] = "grape"
print(id(this list))
print(id(thislist[0]))
output:
1
2
47251449707712
47251450602288
The element’s location changed, but the list’s placement remained the same. It denotes the creation of a new object for the element and its saving in the list. The term “mutable” refers to this. An immutable object cannot change its state or contents after being created, although a mutable object may.
Tuples are called pseudo-immutable; though they are immutable they can contain mutable objects whose values can be modified.
1
2
3
mytuple = (1, 2, 3, [4, 5, 6])
print(id(mytuple))
print(id(mytuple[-1]))
output:
1
2
22916022675872
22916023512128
1
2
3
4
mytuple[-1].append(7)
print(id(mytuple))
print(id(mytuple[-1]))
print(mytuple)
output:
1
2
3
22916022675872
22916023512128
(1, 2, 3, [4, 5, 6, 7])
As the above code exhibits, we can alter the values of immutable objects, i.e., the list contained within the tuple.
With tuple packing and unpacking, we can assign values to a tuple of elements from another tuple in a single line.
1 2 3 4 5
mytuple = ("apple", "banana", "cherry") a, b, c = mytuple print(a) print(b) print(c)
output:
1 2 3
apple banana cherry
Although tuple values cannot be modified, you can alter them by turning them into a list with list(). When you are finished with your data processing, you can use the tuple function to convert it back to a tuple().
1 2 3 4 5 6 7 8
mytuple = ("apple", "banana", "cherry") conv_list = list(mytuple) print(type(conv_list)) conv_list.append("grape") print(conv_list) tuple_fruits = tuple(conv_list) print(type(tuple_fruits)) print(tuple_fruits)
output:
1 2 3
< class 'list' > ['apple', 'banana', 'cherry', 'grape'] < class 'tuple' > ('apple', 'banana', 'cherry', 'grape’)