Chapter 3
List
With what we have learnt in Chapter 2 let us face an imaginary problem. You have
measured a mass 5 times and want to do some calculations with it. What will you
do? Will you use 5 variables? What would happen if you had measured 100 times
or 10000?
Being science students you certainly are thinking of a matrix or a vector. However,
For a true taste of matrix in Python we will have to wait till we learn about “numpy“.
Till then we will use a very basic data type in Python that is called a list
3.1 List
Have you ever prepared a shopping list? list in Python are similar.
mass = [2.0, 2.2, 2.1, 2.3, 2.2]
In the code above we have a list of 5 measurements of a given mass. The numbers t The space between two
numbers are optional and
are simply enclosed by square brackets [] and each value is separated by commas.
can be used for better read-
In chapter 2 we learnt about integer, float, complex and string data type. A list ability of the code.
can contain any or all of these data types. It is basically a container in which we
can place other data types in a defined sequence and it is mutable.
>>>mylist = [ 5, 2.0, "apples", 2+3j] t mutable is something
which can be modified
after it is created.
In the list named mylist there are 4 values which are called elements. To print a
list we can use the print command.
>>>print(mylist) t Note the difference in line
2 and 4: if you print any el-
[5, 2.0, 'apples', (2+3j)]
ement of the list the square
>>>print(mylist[1]) bracket is not printed,
2.0
25
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link] Chapter 3 List
As we can see in line 1 and 2 the print command prints the whole list along with
the square brackets. To print a specific element we can add the index of the
element, as seen in line 3 and 4 above. Have you noticed that print(mylist[
1]) prints the second element i.e 2.0 and not 5. This is because Python is zero
indexed. That means we start counting from zero.
The 0t h element is 5 which is an integer. The 1st element is 2.0 which is a float.
The 2nd element is ”apples“ which is an string. The 3r d element is 2+3j which is
complex. Thus you can see that, while our first list called mass was a list of floats,
the second list called mylist is a collection of 4 different types of data.
It is easy to get the last element of the list, even if you don’t know how many
elements are there. simple use the index -1. For the second last element use -2,
etc.
t In the last line note how we >>>print(mylist[-1])
have used the element as
(2+3j)
any other variable.
>>>print(mylist[-2])
apples
>>>print("The mass is %d "%mylist[1] )
The mass is 2
3.1.1 Manipulating a list
While printing elements of a list we learnt how to use the index. The same index
can be used to change the list.
>>>print(mylist)
[5, 2.0, 'apples', (2+3j)]
>>>mylist[0] = "changed"
>>>print(mylist)
['changed', 2.0, 'apples', (2+3j)]
t You can change replace any In the above code note how the element 0 of mylist has been changed to "changed".
element with another value,
We had learnt that lists are heterogeneous in the sense they can contain different
you can also change the
type of data it holds. data types. Here we saw that an element which was an integer has been replaced
by a string.
Sometimes we only need a part of the list for this you can just slice it. Just like
apiece of cake!!.
>>>mylist = [10, 20, 30, 40, 60, 3, 7, 9, 10, 2]
>>>print(mylist[0:3])
[10, 20, 30]
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
3.1 List Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
In line 2 we use the following syntax list[start:stop]. Note that our stop
index was 3 which correspond to element with value 40 but 40 not printed in line
3. What went wrong?
Nothing. Remember, while slicing the stop value is the first index which will not
be included in the sice, i.e. your selection ends at index stop-1. The element with
index start will be included in the list.
We can have the following cases:
list[start:stop] # Slice contains index start to stop-1
list[start:] # By skipping the stop index the slice contains index
start to end of array including last element.
list[:stop] # Skipping the start index begins the slice at index 0.
list[:] # By skipping both index the slice is the whole list.
t Line 8 may look useless
let us see some real examples.
but we shall understand it’s
>>>mylist = [10, 20, 30, 40, 60, 3, 7, 9, 10, 2] value later
>>>print(mylist[0:3])
[10, 20, 30]
>>>print(mylist[5:])
[3, 7, 9, 10, 2]
>>>print(mylist[:4])
[10, 20, 30, 40]
>>>print(mylist[:])
[10, 20, 30, 40, 60, 3, 7, 9, 10, 2]
While slicing there is another parameter we can use that is the step value. lefthand Slicing list returns a copy,
the original is not changed.
list[start:stop:step] # Slice contains index start to stop-1 by [Link] Numpy arrays re-
turns a view that shares
The step value can be used with any of the above cases.
memory with the original.
>>>mylist = [10, 20, 30, 40, 60, 3, 7, 9, 10, 2]
>>>print(mylist[0:9:3])
[10, 40, 7]
>>>print(mylist[3:8:2])
[40, 3, 9]
in line 2 and 3 we see start value 0, stop value 9 and skip value 3. So the slice
contains the first element at index 0 i.e 10. It then skips 3 elements including 10
and prints 40, it skips 3 more including 40 and prints 7, it skips 3 more including
7 and the next element would have been 2 but its index is 9 and the last element
Python includes is stop-1 i.e 8 so 2 is not printed.
L don’t worry if you cannot
Similarly, step value may be a negative number:
understand negative step.
list[::-1] # all items in the array, reversed Come back to them later.
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link] Chapter 3 List
list[1::-1] # the first two items, reversed
list[:-3:-1] # the last two items, reversed
list[-3::-1] # everything except the last two items, reversed
Be careful while using step value -1, if the element does not exit it will not give an
error but return a empty list or the last value depending on your Python version.
3.1.2 Methods of list
t You will understand the
term method later while List has some in built ”tools“ that we will call methods. Using these methods a
studying ”Object Oriented number of tasks can be easily performed.
Programming“.
Adding elements to the end of the list
It’s a common practice to start with a empty list and grow it by adding elements.
For this we can use the append() method.
t As the name suggests >>>data = []
append() will append the
>>>print(data)
element to the end of the
list. []
>>>[Link](2.0)
>>>print(data)
[2.0]
>>>[Link]("mangoes")
>>>print(data)
[2.0, 'mangoes']
Inserting elements into a list
The append() method always adds the elements to the end of the list, so the index
was not required. However, as we are inserting an element into a list we must
specify the index where we want to insert.
t Note how the index of >>>print(data)
”mangoes“ has changed
[2.0, 'mangoes']
to 2 after insertion.
>>>[Link](1,2.4)
>>>print(data)
[2.0, 2.4, 'mangoes']
Line 3 inserts the value 2.4 at index 1. The element after the point insertion will
be shifted to the right by one step.
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
3.1 List Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
Removing all the elements from a list
If you want to clear all the elements from a list use the clear() method. How
simpler can it get?
>>>print(data) B Even though there are no
index or values used the
[2.0, 2.4, 'mangoes']
parenthesis () must be used.
>>>[Link]()
>>>print(data)
[]
>>>
Removing a element at specified position in a list
The pop() method can be used to remove an element by specifying it’s index. The
removed value can be stored in another variable for use if needed.
>>>mylist = [ 5, 2.0, "apples", 2+3j]
>>>x = [Link](2)
>>>print(mylist)
[5, 2.0, (2+3j)]
>>>print(x)
apples
>>>[Link]()
(2+3j)
>>>print(mylist)
[5, 2.0]
»>mylist = [ 5, 2.0, "apples", 2+3j] »>del(mylist[2]) »>print(mylist) [5, 2.0, (2+3j)]
»>del(mylist) »>print(mylist) Traceback (most recent call last): File "<stdin>", line
1, in <module> NameError: name ’mylist’ is not defined
We can see that by using .pop(2) the element at index 2 i.e. ”apples“ has been
removed from the list and stored in the variable x. In line 7 we see that if omit the
index in .pop() then the last element in the list will be removed. Also, if we don’t
assign the popped element to a variable then it will be printed on the screen as in
line 8.
B Note that del is not a
If you don’t need the removed element and don’t want to suppress the output on method and its syntax is
the screen then you can use the del statement. different del(list[index]
>>>mylist = [ 5, 2.0, "apples", 2+3j]
>>>del(mylist[2])
>>>print(mylist)
[5, 2.0, (2+3j)]
>>>del(mylist)
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link] Chapter 3 List
>>>print(mylist)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'mylist' is not defined
We see from line 5 onwards that if we omit the index then the entire list will be
deleted.
Removing a element from a list by value
Sometimes it may so happen that you want to remove an element, you know the
value but don’t know the index. For such cases you can use the remove() method.
t [Link](2.0) will >>>numbers = [2, 3.0, 2, 2.0]
remove the first element
>>>print(numbers)
or the last element? Try for
yourself
[2, 3.0, 2, 2.0]
>>>[Link](2)
>>>print(numbers)
[3.0, 2, 2.0]
In line 4 we tried to removed the element whose value was 2, but only the first
element has been removed. This is because remove() only removes the first
occurrence of the value.
Sorting a list
Using the sort() method sorting a list is a one line task.
>>>numbers = [2, 3.0, 2, 2.0]
>>>[Link]()
>>>print(numbers)
[2, 2, 2.0, 3.0]
Similarly if we have a list of strings then also we can use the sort() method.
>>>fruits = ["mangoes", "apples", "pear", "banana"]
>>>[Link]()
>>>print(fruits)
['apples', 'banana', 'mangoes', 'pear']
The method sort() changes the list permanently. If you don’t have a backup
then there is no way to recover the original order of the elements.
B Note it is True and False
with capital T and capital F. We saw that sort() sorts the list in ascending order. If we want to sort the list in
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
3.1 List Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
descending order then we have to specify the criteria by using sort(reverse=
True). When we are using sort() we are actually using sort(reverse=False)
which is the default.
>>>numbers = [2, 3.0, 2,2.0]
>>>[Link](reverse=True)
>>>print(numbers)
[3.0, 2, 2, 2.0]
The same is true for a list of characters. However, what happens if we have a
heterogeneous list?
>>>mylist = [ 5, 2.0, "apples", 2+3j]
>>>[Link]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and '
float'
>>>numbers = [2, 3.0, 2,2.0, 3+2j]
>>>[Link]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'complex' and
'float'
The sort() method cannot be used if we have a list in which string, float and
complex are mixed. It does nor work with a homogeneous complex list. How-
ever, a mixed list of integers and float can be sorted.
The method sort() permanently changes the list. However, if only a temporary
sorting is needed that does not change the list (say for printing only) then sorted()
function can be used.
>>>numbers = [2, 1, 5, 7, 3, 5] L sorted() is not a method,
>>>print(sorted(numbers)) note its syntax
[1, 2, 3, 5, 5, 7]
>>>print(sorted(numbers, reverse=True)) t reverse=True can be used
[7, 5, 5, 3, 2, 1] with sorted. See line 4.
>>>x= sorted(numbers)
>>>print(x)
[1, 2, 3, 5, 5, 7]
>>>print(numbers)
[2, 1, 5, 7, 3, 5]
In line 2 we printed the sorted list. In line 4 we sorted the list and assigned it to a
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link] Chapter 3 List
new list however, in line called [Link], in line 10 we see that the original list is
unchanged.
Reversing a list
If you need to reverse a list without any sorting use the reverse() method. The
method revers() changes the list permanently but reversing the list twice gives
you the original list.
>>>numbers = [2, 1, 5, 7, 3, 5]
>>>[Link]()
>>>print(numbers)
[5, 3, 7, 5, 1, 2]
Counting the number of elements in a list having a given value
The count() method returns the number of elements in the list that has the given
value.
>>>numbers = [2, 1, 5, 7, 3, 5]
>>>print([Link](5))
2
The element 5 occurred twice, so the count() method returned 2.
Merging two list
say we have two list and want to merge the two. For this we can use the extend()
method.
>>>list1 = [1, 2, 3]
>>>list2 = ["atom", "molecules"]
>>>[Link](list2)
>>>print(list1)
[1, 2, 3, 'atom', 'molecules', 'atom', 'molecules']
>>>print(list2)
['atom', 'molecules']
In line 1 and 2 we have two different lists. in line 3 list 2 is appended to list 1. This
changes the list1 but list2 remains unchanged.
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
3.1 List Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
Copying a list
We all love to copy and also to paste. Study the code below.
>>>list1 = [1, 2, 3, 4, 5]
>>>copyoflist1 = list1
>>>print(copyoflist1)
[1, 2, 3, 4, 5]
>>>copyoflist1[1] = 1000
>>>print(copyoflist1)
[1, 1000, 3, 4, 5]
>>>print(list1)
[1, 1000, 3, 4, 5]
From line 3 and 4 it seems that we have prepared a copy of list1 in line 2. However,
when we make a change in the copyoflist1 by replacing the element at index 1
with a value 1000, list1 also changes. This is because Python did not make a copy
of the list in line 2, copyoflist1 is just another reference to list1.
There are two easy way out of this situation. We can use the copy() method or
copy using slicing.
>>>list1 = [1, 2, 3, 4, 5]
>>>truecopyoflist1 = [Link]()
>>>print(truecopyoflist1)
[1, 2, 3, 4, 5]
>>>truecopyoflist1[1] = 10000
>>>print(truecopyoflist1)
[1, 10000, 3, 4, 5]
>>>print(list1)
[1, 2, 3, 4, 5]
We can see from line 8 and 9 that now we have two different lists. The second
method is by using slicing which we learnt in section 3.1.1.
>>>truecopyoflist1 = list1[:] L An easier way to check if
>>>print(id(list1)) two objects (list are also
objects) are same or differ-
140000319259016
ent is by use the Python’s
>>>print(id(truecopyoflist1)) in built function id(). In
140000319287944 Python every object has an
unique identity.
In line 2 we are slicing the list1 to include all elements. We know we have a new
list as the two is’s are different. The id of the list will have different numbers on
you computer.
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link] Chapter 3 List
One last method ...phew!!
In python list has 11 methods. We have discussed 10 so why leave the last one.
The last method is index(). It returns the position (index) of the first occurrence
of an element.
>>>list1 = [1, 2, 3, 4, 5]
>>>list1 = [1, 2, 1, 4, 5]
>>>print([Link](1))
0
The element 1 occurs twice but index() will only return the first occurrence.
3.1.3 Index error and length of a list
It is quite common to encounter errors like the one given below.
>>>list1 = [1, 2, 3, 4, 5]
>>>print(list1[5])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
Index out of range is so common mistake for beginners that it has name ”index
error“. It simply means that Python did not find an element in the list at the index
you specified. If you examine the code above at first glance it seems normal to
access list1[5] as there five elements in the list. However, you must keep in mind
that PYTHON IS ZERO INDEXED. That is the counting of the index starts from
zero and not one. So, index 4 is the fifth and last element of the given list.
The first thing you should check on seeing such error is the length of the list and
remember the index of the last element is one less than the length. To check the
length you can use the len() function.
>>>list1 = [1, 2, 3, 4, 5]
>>>len(list1)
5
Another way to check the last element would be to use the -1 index as discussed
earlier.
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
3.1 List Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]
3.1.4 Summary
You may be wondering why do we have a full chapter dedicated for list. The
simple answer is that in Python it is the most used and a powerful data type. We
will also be studying two more Python data type tuple and dictionary but for
physics problems you will be using them less often. Till you learn about numpy
arrays list shall be the data type of choice.
Method Description CHANGE LANGUAGE Example
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Remember for [Link]()
3.1.5 Exercise
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link]