Lists
Lists
1. Introduction to Collections
The previous lessons have covered how to store and manage a single value in a
variable. The following example illustrates how it is achieved.
>>> name = ‘Rohan’
>>> age = 20
Often solving problems demand multiple values to be stored in a single variable.
Suppose you want to roll a dice n times and store its values. A straightforward approach
is to use one variable per value of a roll as illustrated below.
>>> roll_1 = value_1
>>> roll_2 = value_2
>>> roll_3 = value_3
…………………
>>> roll_n = value_n
However, this approach has several problems. First, what if you do not know the value
of n beforehand. Assume you want to develop a program where users can store the
goods they buy in a supermarket. One day they might buy 10 goods, and another day,
they might buy 100 goods. Hence, one cannot decide in advance how many variables
are needed. Second, what if the value of n is very large (e.g., n = 10,000). Creating and
managing 10,000 variables is a difficult task.
Using container data types will solve these problems. Container data types allow storing
more than one value in a variable. In the rolling dice example, using container data
types, all the n values can be stored in a single variable. How to do that will be covered
in Section 2. Python supports many container data types. Some of them are List, Tuple,
Range, and Set. Note that there are many more. This lesson discusses the List in detail.
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 illustrates the structure of a list where the values are
comma-separated and are surrounded by square brackets. More examples of lists in
Python are as follows.
>>> list_1 = [1, 2, 3, 4, 5, 6]
>>> list_2 = [‘a’, ‘b’, ‘c’, ‘d’]
>>> list_3 = [‘apple’, ‘orange’, 2000, 69.6]
These examples illustrate an important property of lists in Python which is that the
values within a list need not be of the same data type. For example, in list_3, ‘apple’ and
‘orange’ are strings, 2000 is an integer, and 69.6 is a floating-point number.
The following Python code illustrates how to access the values in a list.
>>> values = [15, 20, 96, 32, 17]
>>> print(values[0])
15
>>> print(values[4])
17
In addition to accessing a single value at a time, Python also allows extracting a section
of values from a list. The following code illustrates how it is achieved.
>>> values = [15, 20, 96, 32, 17]
>>> print(values[0:3])
[15, 20, 96]
>>> print(values[2:5])
[96, 32, 17]
It is evident from the above examples that if the specified index range is [m:n], the
values considered are from index m to index (n-1). For example, values[0:3] considers
the values from 15 to 96 where 15 is at index 0 and 96 is at index 2 (not 3).