You are on page 1of 10

Lesson 6: Python Lists II

Teacher-Student Activities
In the previous lesson, we learnt two more functions of Python Lists. They are append() and
count() . In this lesson, we will learn Python lists in more detail.

Activity 1: Multiple Data Types


A Python list can store values of different types. Recall that in the trial class we created 4 different
variables to store the attributes of a planet.
Mercury

Diameter (km) 4879

Gravity ($m/s^2$) 3.7

Ring No

Let's store the name of a planet, its diameter, gravity and whether it has a ring or not in a Python list.

Q: But before that do you remember the different data-types in python?

Ans: There are four different data-types. They are:

1. int - a numeric value without a digit after the decimal point. For example: 13, -244 etc.

2. float - a numeric value with a digit after the decimal point. For example: 2.71, -3.14898
etc.

Note: Both the int and float values can be positive or negative or 0 .

3. str (stands for string) - any value enclosed within single ( ' ' ) or double ( " " ) quotes. For
example: 'Windows 10', '15 August 1947' etc.

4. bool (stands for boolean) - either True or False .

1 # Student Action: Create a list which contains "Mercury", its diameter, gravity and whethe
2 planet = ['Mercury', 4879, 3.7, False]
3 planet

['Mercury', 4879, 3.7, False]


Activity 2: List Length
To see how many items are stored in a list, you can use a function called len() .

1 # Student Action: Find the number of items stored in the 'planet' list.
2 len(planet)
3

Activity 3: List Indexing And The for Loop^^^


A list index is similar to your roll number in your class in the school. But here's a catch: The roll
number of the rst student in your class will be 1 . On the other hand, the roll number of the rst
item in a Python list is 0 .

For example: In the 'planet' list, the rst item is "Mercury" so its index is 0 .

To get an item located at each index in a list, just write the list name followed by the square
brackets [] and inside the brackets, enter the index number.

Syntax: list_name[index_number]

Note: The list indexing concept will be used throughout this course. So practice it as much as you
can. It is a very simple concept to learn.

1 # Teacher Action: Print the items at each index in the 'planet' list.
2 print("Item 1:",planet[0])
3 print("Item 2:",planet[1])
4 print("Item 3:",planet[2])
5 print("Item 4:",planet[3])

Item 1: Mercury
Item 2: 4879
Item 3: 3.7
Item 4: False

Imagine that you have a list containing 100 items. Getting each item of that list using this method
will not be feasible. In such cases, you can retrieve every item using a for loop.

Let's rst learn the for loop. We will print the rst 10 natural numbers using a for loop. Once we
learn how a for loop works, we will retrieve all the items of the planet list using the list indexing
method and through the for loop.
In the for loop, we will use a ready-made function called range() which generates consecutive
natural numbers between two speci c numbers.

1 # Teacher Action: Print the first 10 natural numbers using the 'for' loop.
2 for i in range(1,11):
3 print(i)

1
2
3
4
5
6
7
8
9
10

In natural language, the above code can be read as for every number in the range of 1 to 11 and
except 11 , print a number. So, in the range of 1 to 11 and except 11 , there are 10 numbers
starting from 1 to 10 . So, all these numbers in this range will get printed one-by-one.

Here, the range() function is used to de ne a range of numbers. It takes two numbers as input; a
starting number and an ending number to de ne a range. However, the ending number is used just
as a stopping point. The ending number is NOT included in the range.

Note:

1. If you don't give a starting point in the range() function, then Python assumes that your
starting point is 0 .

2. If you enter n as an input to the range() function, then it will generate all the numbers
starting from 0 till n - 1 . For e.g., if n = 5 , then the range() function will generate ve
numbers starting from 0 till 4 .

Now, let's retrieve all the values of the planet list using the for loop.

1 # Teacher Action: Using 'for' loop, print each element of the 'planet' list.
2 # 1. First, find out how many items are there in the 'planet' list and store it in the var
3 n=len(planet)
4 # 2. Now iterate through each item using the for loop.
5 for x in range(0,n):
6 # 3. Now, write the print() function with 'i' and 'planet[i]' as inputs.
7 print("Item at index:",x,"is",planet[x])

Item at index: 0 is Mercury


Item at index: 1 is 4879
Item at index: 2 is 3.7
Item at index: 3 is False

Here:

The value of num_items is 4 because the length of the planet list is 4 as it contains 4
items.

The range() function, takes 4 as input and generates numbers from 0 to 3 . The number 4
is excluded.

The value of i also goes from 0 to 3 . Hence, planet[i] goes from planet[0] to
planet[3] . Essentially, the variable i stores the values generated by the range() function,
but only one value at-a-time.

So, for every value of i the print() function takes planet[i] as input and prints each item
contained in the planet list.

There is another way to get all the items from a Python list using a for loop.

1 # Teacher Action: Demonstrate another way of getting all the items from a list using the '
2 for item in planet:
3 print(item)

Mercury
4879
3.7
False

Here, the variable i does not take the numeric value because the range() function is not used
here. So, the value of i goes from the rst item of the list till the last item in the list.

The second method will not work if you want to retrieve all the items from a list in the reverse order.
Hence, you will have to use the rst method.

So, in this case, using the for loop with the range() function, retrieve all the items of the planet
list in the reverse order.

1 # Student Action: Print every item of the 'planet' in the reverse order, using the 'for' l
2 n = len(planet)
3 for i in range(0, n):
4 print(planet[n-1-i])

False
3.7
4879
Mercury
In the above code, the value of n is 4 . So, the range() function generates the numbers 0 to 3 .
The value of i will also go from 0 to 3 . Thus, planet[n - 1 - i] will go from planet[3 - 0] to
planet[3 - 3] .

And this is why we get the items of the planet list in the reverse order.

Negative Indexing:

You can also use negative indices to get items from a list. They are helpful in retrieving items from a
list in the reverse order.

The negative indices begin with -1 and go till -n where n is the number of items in a list.

The last item in a list is located at -1 index. Similarly, the rst item in a list is located at -n index.

1 # Student Action: Use the negative indices to retrieve all the items from the 'planet' lis
2 for i in range(-n, 0):
3 print(planet[i])
4

Mercury
4879
3.7
False

1 # Student Action: Using the 'for' loop and negative indices, retrieve all the items from t
2 for i in range(1, n+1):
3 print(planet[-i])

False
3.7
4879
Mercury
Activity 4: List Slicing
Suppose that I have a list of 10 cars that I own.

my_cars = ['Chrysler', 'Lamborghini', 'Bugatti', 'Porsche', 'Ford', 'Rolls Royce',


'Suzuki', 'Bentley', 'Lexus', 'Tesla']

Let's say, I want to see a list of only rst ve cars, then I can use the concept of list slicing.

To slice a list, write the name of the list followed by square brackets and inside the square brackets,
enter the starting point (in this case it is zero) followed by a colon sign ( : ) and the ending point.

Syntax: list_name[start_index:end_index]

Note that the item at the end-index will not be a part of the sub-list.

1 # Teacher Action: Retrieve the items from a list using the slicing method by mentioning bo
2 my_cars = ['Chrysler', 'Lamborghini', 'Bugatti', 'Porsche', 'Ford', 'Rolls Royce', 'Suzuki
3 my_cars[2:7]

['Bugatti', 'Porsche', 'Ford', 'Rolls Royce', 'Suzuki']

In my_cars[0:5] sub-list, the item at index 5 will not be included in the sub-list. The sub-list will
contain the items ranging from indices 0 to 4 from the parent list.

If you do not specify the starting point, then Python assumes that you want to get the items starting
from the rst item of the list.

1 # Teacher Action: Retrieve the first 5 items from the 'my_cars' Python list without mentio
2 print(my_cars[:5])
3 print(my_cars[5:])
4 print(my_cars[:])

['Chrysler', 'Lamborghini', 'Bugatti', 'Porsche', 'Ford']


['Rolls Royce', 'Suzuki', 'Bentley', 'Lexus', 'Tesla']
['Chrysler', 'Lamborghini', 'Bugatti', 'Porsche', 'Ford', 'Rolls Royce', 'Suzuki', 'Bent

Now, using the list slicing concept, you print all the cars stored in the my_cars list starting from
'Lamborghini' to 'Bentley' .

1 # Student Action: Write a code to see all the cars in the list starting from 'Lamborghini'
2 my_cars[1:8]

['Lamborghini',
'Bugatti',
'Porsche',
'Ford',
'Rolls Royce',
'Suzuki',
'Bentley']

You can also skip intermediate items while retrieving a few other items from a list.

Suppose you want to retrieve alternate items from a list starting from the rst item, then you can
use the list slicing method.

Inside the square brackets, after the ending point, you have to include another colon ( : ) sign
followed by the number of items to be skipped.

Syntax: list_name[start_index:end_index:num_of_items_to_be_skipped]

1 # Student Action: Retrieve all the alternate items from the 'my_cars' list.
2 my_cars[0:10:2]

['Chrysler', 'Bugatti', 'Ford', 'Suzuki', 'Lexus']

Note: If you are retrieving all the items from a list, then you actually do not have to mention the start
and end indices. Just put the colon ( : ) signs and Python will know that you wish to retrieve all the
items.

To retrieve all the items from a list in the reverse order, you can also use the list slicing method with
a negative index -1 after the second colon ( : ) sign.

1 # Student Action: Retrieve all the items from the 'my_cars' list in the reverse order.
2 my_cars[::-1]

['Tesla',
'Lexus',
'Bentley',
'Suzuki',
'Rolls Royce',
'Ford',
'Porsche',
'Bugatti',
'Lamborghini',
'Chrysler']

Activity 5: Index Of An Item


Suppose that you want to nd the index of Ford in the my_cars list, then you can use the index()
function.
To nd an index of an item, write the name of the list followed by the dot (.) operator followed by
the index() function. Inside the index() function, enter the item whose index you wish to nd.

Syntax: list_name.index(item)

1 # Student Action: Find the index of 'Ford'.


2 my_cars.index('Ford')

So, the item 'Ford' exists at the index = 4 in the my_cars list.

1 # Student Action: Find the index of 'Rolls Royce'.


2 my_cars.index('Rolls Royce')

And the item 'Rolls Royce' exists at the index = 5 in the my_cars list.

Activity 6: Removing An Item


Let's say you sold your 'Bentley' car to your friend. So, you will have to remove it from the list of
your cars.

To remove an item from a list, use the remove() function followed by the item that you wish to
remove.

Syntax: list_name.remove(item)

1 # Student Action: Remove 'Bentley' from the 'my_cars' list.


2 my_cars.remove('Bentley')
3 print(my_cars)

['Chrysler', 'Lamborghini', 'Bugatti', 'Porsche', 'Ford', 'Rolls Royce', 'Suzuki', 'Lexu

Now, 'Bentley' is a not part of my_cars list anymore.


Activity 7: The pop() Function^
You can also remove an item from a list using another function called pop() . It has two behaviours.

Behaviour I: If you do not specify any input, it will always remove only the last item from a Python
list.

Syntax: list_name.pop()

1 # Student Action: Remove the last item from the 'my_cars' list using the 'pop()' function.
2 v=my_cars.pop()
3 print(v)
4 print(my_cars)

Tesla
['Chrysler', 'Lamborghini', 'Bugatti', 'Porsche', 'Ford', 'Rolls Royce', 'Suzuki', 'Lexu

Behaviour II: If you want to remove an item from a list located at a speci c index, then pass the
index of that item as an input to the pop() function.

Syntax: list_name.pop(item_index)

1 # Student Action: Remove the item at 'index = 3' from the 'my_cars' list using the 'pop()'
2 v = my_cars.pop(3)
3 print(v)
4 print(my_cars)

Porsche
['Chrysler', 'Lamborghini', 'Bugatti', 'Ford', 'Rolls Royce', 'Suzuki', 'Lexus']

Activity 8: Item Replacement^^


You can replace an existing item in a list with a new item. Suppose I exchanged my Suzuki car with
a McLaren car. So, I need to update my_cars list accordingly.

To replace an item, rst get the index of that item. Then using the list indexing method, replace the
existing item with the new one.

Syntax: list_name[list_name.index('current_item')] = new_item

1 # Student Action: Replace 'Suzuki' with 'McLaren' in the 'my_cars' list.


2 i = my_cars.index('Suzuki')
3 my_cars[i] = 'McLaren'
4 print(my_cars)
['Chrysler', 'Lamborghini', 'Bugatti', 'Ford', 'Rolls Royce', 'McLaren', 'Lexus']

As you can see, the 'Suzuki' car has been replaced by 'McLaren' using the list indexing method.

Similarly, you replace 'Lexus' with 'Aston Martin' using the list indexing method.

1 # Student Action: Replace 'Lexus' with 'Aston Martin' in the my_cars list.
2 my_cars[my_cars.index('Lexus')] = 'Aston Martin'
3 print(my_cars)

['Chrysler', 'Lamborghini', 'Bugatti', 'Ford', 'Rolls Royce', 'McLaren', 'Aston Martin']

As you can see, the 'Lexus' car has been replaced by 'Aston Martin' using the list indexing
method.

You might also like