4.1) List
1. Introduction to Collections
The preceding lectures addressed
storing and managing a single value in a variable. The following example shows
how it is done.
>>>
name = ‘Rohan’
>>>
age = 20
Often, solving issues necessitates
storing numerous values in a single variable. Assume you wish to roll a dice n
times and save the results. As seen below, a simple way is to utilize one
variable for each value of a roll.
>>>
roll_1 = value_1
>>>
roll_2 = value_2
>>>
roll_3 = value_3
…………………
>>>
roll_n = value_n
This strategy, however, has
significant flaws. First, what if you don't know the value of n in advance?
Assume you want to create an application that allows users to save items
purchased at a supermarket. They may purchase ten items one day and one hundred
items the next. As a result, the number of variables required cannot be
determined in advance. Second, what if n is really huge (for example, n =
10,000)? It is tough to create and manage 10,000 variables.
These issues will be resolved by using
container data types. Container data types let you to store many values in a
variable. Using container data types, all n values in the rolling dice example
may be kept in a single variable. Section 2 will explain how to do so. Python
offers a wide range of container data types. List, Tuple, Range, and Set are a
few examples. There are plenty others. This course goes through the List in
great depth.
2. Introduction to Lists
List is one of the popular data
structures. A list holds comma-separated values between square brackets.
Following is a sample list in Python.
>>> numbers = [1, 2, 3, 4]
The above example clearly demonstrates
the structure of a list with comma-separated items enclosed by square brackets.
Here are some more Python list examples.
>>>
list_1 = [1, 2, 3, 4, 5, 6]
>>>
list_2 = [‘a’, ‘b’, ‘c’, ‘d’]
>>>
list_3 = [‘apple’, ‘orange’, 2000, 69.6]
These examples demonstrate an
essential aspect of Python lists: the values in a list do not have to be of the
same data type. In list 3, for example, the strings 'apple' and 'orange' are
strings, the integer 2000 is an integer, and the floating-point value 69.6 is a
floating-point number.
3. Accessing
Values in a List
A normal list will include several
values. The first step in accessing the values in a list is to locate the
values. Assume you go to the library and need to inform the librarian the book
you require. Assume the books are stored on shelves. First, identify the shelf
on which the book is situated. Second, you should identify where the book is on
the shelf (e.g., the second book from the left). Similarly, accessing the
values in a list is similar.
To locate the values in a list, the
lists in Python are indexed. Consider the following Python list.
>>> values = [15, 20, 96, 32, 17]
Figure 1 illustrates how the above
list is indexed.
Two important properties of indexing
are,
- ·
The index of the
first value is 0 (not 1).
- ·
In Figure 1,
the first value 15 is indexed 0.
- ·
The values are
indexed from left to right
Figure 1 shows that the first number,
15, is indexed as 0, the second value, 20, is indexed as 1, and the third
value, 96, is indexed as 2.
The following Python code explains how
to access the values in a list.
>>>
values = [15, 20, 96, 32, 17]
>>>
print(values[0])
15
>>>
print(values[4])
17
Python allows you to extract a chunk
of values from a list in addition to obtaining a single item at a time. The
code below demonstrates how it is done.
>>>
values = [15, 20, 96, 32, 17]
>>>
print(values[0:3])
[15,
20, 96]
>>>
print(values[2:5])
[96,
32, 17]
The above examples demonstrate that if
the provided index range is [m:n], the values examined are from index m to
index n. (n-1). For example, values[0:3] takes into account values ranging from
15 to 96, where 15 is at index 0 and 96 is at index 2. (not 3).
4. Appending
Values to a List
Consider the values list which was used in the previous sections.
values = [15, 20, 96, 32,
17]
The append() function may be used to
append 60 to this list, which means adding 60 to the end of this list. The
following code explains how to utilize the add() function.
>>>
values = [15, 20, 96, 32, 17]
>>>
values. append(60)
>>>
print(values)
[15,
20, 96, 32, 17, 60]
The output shows that 60 has been
appended successfully.
5. Updating a
Value in a List
Consider the values list
which was used in the previous sections.
values = [15, 20, 96, 32, 17]
Assume we need to change the value at
index 2 from 96 to 60. It is possible to accomplish this in the following way.
>>>
values = [15, 20, 96, 32, 17]
>>>
values[2] = 60
>>>
print(values)
[15,
20, 60, 32, 17]
To update the value at a certain
index, we put the name of the list in square brackets on the left-hand side of
the equal notation, followed by the index in square brackets on the right-hand
side of the equal notation (e.g., values[2] = 60).
6. Deleting a
Value from a List
Consider the values list
which was used in the previous sections.
values
= [15, 20, 96, 32, 17]
Suppose we need to delete the value at
index 1. It can be achieved using the remove() method as shown below.
>>>
values = [15, 20, 96, 32, 17]
>>>
values.remove(20)
>>>
print(values)
[15,
96, 32, 17]
The result does not contain the number
20 from index 1. One disadvantage of utilizing the delete() technique is that
the value at the given position must be known. In the above example, for
example, the delete() function cannot be used since we do not know that 20 is
the value at index 1. When the value at a given index is unknown, another way
is to use the del (remove) keyword. Consider the following illustration.
>>>
values = [15, 20, 96, 32, 17]
>>>
del values[1]
>>>
print(values)
[15,
96, 32, 17]
The del keyword does not
need the value at an index to be known.
7. Multi-dimensional Lists
So far, we've just looked at one-dimensional lists with values enclosed in square brackets. Python also supports the building of multi-dimensional lists. Take a look at the matrix shown in Figure 2.
If you are unfamiliar with the concept of a matrix, consider it as a simple structure where values are stored in multiple rows and columns. A value in a matrix is denoted by amn where m is the row number and n is the column number (see Figure 2).
In Python, representing matrices is as
simple as using 2-dimensional lists. The matrix seen in Figure 3 is stored in
the 2-dimensional list below.
There are three lists inside another
list. Each internal list holds the values of a row in the matrix. For example,
the first internal list contains the values [1,1,1] which is the first row in
the matrix.
Getting to the values in a
2-dimensional list is comparable to getting to the values in a matrix. Assume
we want to get the value in the middle square (a22). It is at index 1 in the
2-dimensional list data, and it is at position 1 again within that internal
list. The code below demonstrates how to access values in a two-dimensional
list.
>>> data = [[1,1,1], [2,2,2],
[3,3,3]]
>>> print(data[1][1])
2
Other list operations such as update,
append, and delete also work in a similar manner. See the example below.
>>> data = [[1,1,1], [2,2,2], [3,3,3]]
>>>
data[1][1] = 25
>>>
print(data)
[[1,1,1],
[2,25,2], [3,3,3]]
>>>
data[1].append(2)
>>>
print(data)
[[1,1,1],
[2,25,2,2], [3,3,3]]
8. List
Operations
This section goes over several other
common list operations.
Ø Length
To find the size/length of a list, the
function ‘len’ (stands for length) can be used. See the following example.
>>> len ([1,2,3])
3
The length of this list is 3 as the
list contains 3 values.
Ø Concatenation
>>>
a = [1,2,3]
>>>
b = [4,5,6]
>>>
print(a+b)
[1,
2, 3, 4, 5, 6]
Suppose there are two lists a and b.
The contents of lists a and b can be combined using the plus(+) operator. a+b
will output a single list with contents from lists a and b. In the output of
the above example, values 1, 2, and 3 are from list a, and values 4, 5, and 6
are from list b.
Ø Repetition
The following code illustrates how
repetition works.
>>>
print([‘Hi’] * 4)
[‘Hi’,
‘Hi’, ‘Hi’, ‘Hi’]
Ø Membership
checks whether a value is available in a list.
See the following example.
>>> print(3 in [1,2,3])
The ‘in’ operator is used to check
membership. Statement ‘3 in [1,2,3]’ checks whether value 3 is available in the
list. Since the value is available, it returns True. If the value is not
available, it will return False.
Ø Iteration
Iteration means going through the list
one element at a time.
>>>
for x in [1,2,3]:
print(x)
1
2
3
The variable x will be assigned to the
first entry in the list, which is 1 in the example above. The print(x) command
will then be executed. The variable x will then be allocated the second value
in the list, which is 2. The print(x) command will be repeated. This pattern
continues until the list's final element. It may not be evident at this stage.
The notion of iteration will be covered in depth in the following lesson.
9. Indexing and
Slicing
We already know that indices are
needed to retrieve values in a list. This section discusses indexing and
introduces a new indexing method known as negative indices. Consider the
following list: L=['a', 'b', 'c']. Table 1 shows a series of Python expressions
and their outcomes to demonstrate how indexing and slicing function.
|
Python Expression |
Result |
Description |
|
L[2] |
'c' |
Indices start at zero |
|
L[-2] |
'b' |
Negative indexing is from right to
left |
|
L[1:] |
['b', 'c'] |
Slicing extracts sections |
- Negative Indices
Figure 4 illustrates how the list L is
indexed using normal indexing and negative indexing.
The last item of the list is indexed
-1 with negative indexing, just as the initial value is indexed 0 in normal
indexing. The remaining components are ordered from right to left. The final
element, 'c,' is indexed -1 in the provided example, the next value to the
left, 'b,' is indexed -2, and 'a,' is indexed -3. As a result, 'print(L[-2])'
returns 'b'.
- Slicing
Slicing is the process of extracting a
portion of a list. We heard about this previously (in Section 3), although
without the name slicing. Using the range m to n within square brackets
(L[m:n]), the values from index m to index n will be considered (n-1). In
addition to what has been described previously, the second element of the range
in L[1:] is empty. It signifies from index 1 to the list's final value. As a
result, L[1:] returns the values 'b' and 'c'.





0 Comments