Chapter 4 - More About Lists
Introduction to Lists
As studied in the previous section, List is a sequence of values of any type. Values in the list
are called elements / items. List is enclosed in square brackets.
Example:
a = [1,2.3,"Hello"]
List is one of the most frequently used and very versatile data type used in Python. A
number of operations can be performed on the lists, which we will study as we go forward.
How to create a list ?
In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string
etc.).
Example:
#empty list
empty_list = []
#list of integers
age = [15,12,18]
#list with mixed data types
student_height_weight = ["Ansh", 5.7, 60]
Note: A list can also have another list as an item. This is called nested lists.
# nested list
student marks = ["Aditya", "10-A", [ "english",75]]
How to access elements of a list ?
A list is made up of various elements which need to be individually accessed on the basis of
the application it is used for. There are two ways to access an individual element of a list:
1) List Index
2) Negative Indexing
65
List Index
A list index is the position at which any element is present in the list. Index in the list starts
from 0, so if a list has 5 elements the index will start from 0 and go on till 4. In order to
access an element in a list we need to use index operator [].
Negative Indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.
In order to access elements using negative indexing, we can use the negative index as
mentioned in the above figure.
Task Sample Code Output
language = p
['p','y','t','h','o','n'] e
Accessing print(my_list[0])
Using List print(my_list[4])
Index language = Y
['p','y','t','h','o','n'] Error! Only Integer
print(my_list[4.0]) can be used for
indexing
Accessing n_list = [“Happy”,[2,0,1,5]] A
Value in a print(n_list[0][1]) 5
nested list print(n_list[1][3])
Accessing day = ['f','r','i','d','a','y'] y
using print(a[-1]) f
Negative print(a[-6])
Index
66
Adding Element to a List
We can add an element to any list using two methods :
1) Using append() method
2) Using insert() method
3) Using extend() method
Using append() method
Task Sample Code Output
List = [] Initial blank
Using print("Initial blank List: ") List:
append() print(List) []
method
# Addition of Elements List after
# in the List Addition:
List.append(1)
[1, 2, 4]
List.append(2)
List.append(4)
print("\nList after Addition :
")
print(List)
# Addition of List to a List List after
List2 = ['Good', 'Morning'] Addition of a
List.append(List2) List:
print("\nList after Addition [1, 2, 4, ['Good',
of a List: ") 'Morning']]
print(List)
Using # Creating a List Initial List:
insert() List = [1,2,3,4] [1, 2, 3, 4]
method print("Initial List: ")
print(List)
List after Insert
# Addition of Element at Operation:
# specific Position
['Kabir', 1, 2, 3,
# (using Insert Method)
List.insert(3, 12) 12, 4]
List.insert(0, 'Kabir')
print("\nList after Insert
Operation: ")
print(List)
Using # Creating a List Initial List:
67
extend() List = [1,2,3,4] [1, 2, 3, 4]
method print("Initial List: ")
print(List) List after Extend
Operation:
# Addition of multiple [1, 2, 3, 4, 8,
elements 'Artificial',
# to the List at the end 'Intelligence']
# (using Extend Method)
List.extend([8, 'Artificial',
'Intelligence'])
print("\nList after Extend
Operation: ")
print(List)
Elements can be added to the List by using built-in append() function. Only one element at a
time can be added to the list by using append() method, for addition of multiple elements
with the append() method, loops are used. Tuples can also be added to the List with the use
of append method because tuples are immutable. Unlike Sets, Lists can also be added to
the existing list with the use of append() method.
Using insert() Method
append() method only works for addition of elements at the end of the List, for addition of
element at the desired position, insert() method is used. Unlike append() which takes only
one argument, insert() method requires two arguments(position, value).
Using extend() method
Other than append() and insert() methods, there's one more method for Addition of
elements, extend(), this method is used to add multiple elements at the same time at the end
of the list.
Removing Elements from a List
Elements from a list can removed using two methods :
1) Using remove() method
2) Using pop() method
68
Using remove() method
Task Sample Code Output
# Creating a List Intial List:
Using List = [1, 2, 3, 4, 5, 6, [1, 2, 3, 4, 5, 6,
remove() 7, 8, 9, 10, 11,12] 7, 8, 9, 10, 11,
method print("Intial List: ") 12]
print(List)
List after Removal:
# Removing elements from List [1, 2, 3, 4, 7, 8,
# using Remove() method 9, 10, 11, 12]
List.remove(5)
List.remove(6)
print("\nList after Removal:
")
print(List)
Using pop() # Removing element from the List after popping
method # Set using the pop() method an element:
List.pop() [1, 2, 3, 4]
print("\nList after popping
an element: ") List after popping
print(List) a specific element:
[1, 2, 4]
# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2) Eleme
print("\nContent after pop ") nts
print(List) can
be
removed from the List by using built-in remove() function but an Error arises if element
doesn't exist in the set. Remove() method only removes one element at a time, to remove
range of elements, iterator is used. The remove() method removes the specified item.
Note – Remove method in List will only remove the first occurrence of the searched element.
Using pop() method
Pop() function can also be used to remove and return an element from the set, but by default
it removes only the last element of the set, to remove an element from a specific position of
the List, index of the element is passed as an argument to the pop() method.
69
Slicing of a List
In Python List, there are multiple ways to print the whole List with all the elements, but to
print a specific range of elements from the list, we use Slice operation. Slice operation is
performed on Lists with the use of colon(:). To print elements from beginning to a range use
[:Index], to print elements from end use [:-Index], to print elements from specific Index till the
end use [Index:], to print elements within a range, use [Start Index: End Index] and to print
whole List with the use of slicing operation, use [:]. Further, to print whole List in reverse
order, use [::-1].
Note – To print elements of List from rear end, use Negative Indexes.
Task Sample Code Output
# Creating a List Initial List:
List= ['G','O','O','D','M','O', ['G','O','O','D','M',
'R','N','I','N','G']
'O',
print("Initial List: ")
'R','N','I','N','G']
print(List)
# using Slice operation Slicing elements in
Sliced_List = List[3:8]
a range 3-8:
print("\nSlicing elements in a
range 3-8: ") ['D', 'M', 'O',
print(Sliced_List) 'R', 'N']
# Print elements from a Elements sliced
# pre-defined point to end from 5th element
Slicing Sliced_List = List[5:]
till the end:
print("Elements sliced from 5th
element till the end: ") ['M', 'O', 'R',
print(Sliced_List) 'N', 'I', 'N', 'G']
# Printing elements from Printing all
# beginning till end elements using
Sliced_List = List[:]
print("\nPrinting all elements
70
using slice operation: ") slice operation:
print(Sliced_List)
['G','O','O','D','M',
'O',
'R','N','I','N','G']
Slicing # Creating a List Initial List:
using List= ['G','O','O','D','M','O', ['G','O','O','D','M',
negative 'R','N','I','N','G']
'O',
index of list print("Initial List: ")
'R','N','I','N','G']
print(List)
# Print elements from beginning Elements sliced
# to a pre defined point using
till 6th element
Slice
Sliced_List = List[:-6] from last:
print("\nElements sliced till 6th ['G','O','O','D','M',
element from last: ") 'O']
print(Sliced_List)
# Print elements of a range Elements sliced
# using negative index List from index -6 to -1
slicing
Sliced_List = List[-6:-1] ['R', 'N', 'I',
print("\nElements sliced from 'N', 'G']
index -6 to -1")
print(Sliced_List)
# Printing elements in reverse Printing List in
# using Slice operation reverse:
Sliced_List = List[::-1]
print("\nPrinting List in reverse:
['G','N','I','N','R',
")
print(Sliced_List) 'O',
'M','D','O','O','G']
71
List Methods
Some of the other functions which can be used with lists are mentioned below:
72
Chapter 5 - Flow of Control and Conditions
In the programs we have seen till now, there has always been a series of statements
faithfully executed by Python in exact top-down order. What if you wanted to change the flow
of how it works? For example, you want the program to take some decisions and do different
things depending on different situations, such as printing 'Good Morning' or 'Good Evening'
depending on the time of the day?
As you might have guessed, this is achieved using control flow statements. There are three
control flow statements in Python - if, for and while.
Flow of
Control and
Conditions
While
If Statement For Statement
Statement
If Statement
On the occasion of World Health Day, one of the schools in the city decided to take
an initiative to help students maintain their health and be fit. Let’s observe an
interesting conversation happening between the students when they come to know
about the initiative.
73
There come situations in real life when we need to make some decisions and based on
these decisions, we need to decide what should we do next. Similar situations arise in
programming also where we need to make some decisions and based on these decisions
we will execute the next block of code.
Decision making statements in programming languages decide the direction of flow of
program execution. Decision making statements available in Python are:
● if statement
● if..else statements
● if-elif ladder
74
If Statement
The if statement is used to check a condition: if the condition is true, we run a block of
statements (called the if-block).
Syntax:
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
If the text expression is False, the statement(s) is not executed.
Note:
1) In Python, the body of the if statement is indicated by the indentation. Body starts with
an indentation and the first unindented line marks the end.
2) Python interprets non-zero values as True. None and 0 are interpreted as False.
Python if Statement Flowchart
75
Example :
#Check if the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)
num = -1
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)
When you run the program, the output will be:
3 is a positive number
This is always printed
This is also always printed.
In the above example, num > 0 is the test expression. The body of if is executed only if this
evaluates to True.
When variable num is equal to 3, test expression is true and body inside body of if is
executed.
If variable num is equal to -1, test expression is false and body inside body of if is skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.
Python if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only when test
condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
76
Python if..else Flowchart
Example of if...else
#A program to check if a person can vote
age = input(“Enter Your Age”)
if age >= 18:
print(“You are eligible to vote”)
else:
print(“You are not eligible to vote”)
In the above example, when if the age entered by the person is greater than or equal to 18,
he/she can vote. Otherwise, the person is not eligible to vote
Python if...elif...else Statement
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, body of else is executed.
77
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart of if...elif...else
Example of if...elif...else
#To check the grade of a student
Marks = 60
if marks > 75:
print("You get an A grade")
elif marks > 60:
print("You get a B grade")
else:
print("You get a C grade")
78
Python Nested if statements
We can have an if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only
way to figure out the level of nesting. This can get confusing, so must be avoided if it can be.
Python Nested if Example
# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
When you run the above program
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
Let’s Practice
Let’s Go through the If-Else Jupyter Notebook to get an experiential learning experience for
If-Else. To download the Jupyter Notebook, go to the following link : http://bit.ly/ifelse_jupyter
Note:
To open Jupyter notebook, go to start menu open anaconda prompt write “jupyter
notebook”
79
The For Loop
The for..in statement is another looping statement which iterates over a sequence of objects
i.e. go through each item in a sequence. We will see more about sequences in detail in later
chapters. What you need to know right now is that a sequence is just an ordered collection
of items.
Syntax of for Loop
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
Flowchart of for Loop
Example: Python for Loop
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
80
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)
when you run the program, the output will be:
The sum is 48
The while Statement
The while statement allows you to repeatedly execute a block of statements as long as a
condition is true. A while statement is an example of what is called a looping statement.
A while statement can have an optional else clause.
Syntax of while Loop in Python
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False. In Python, the
body of the while loop is determined through indentation. Body starts with indentation and
the first unindented line marks the end. Python interprets any non-zero value
as True. None and 0 are interpreted as False.
81
Flowchart of while Loop
Example: Python while Loop
# Program to add natural
# numbers upto
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
When you run the program, the output will be:
Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as our counter variable i is
less than or equal to n (10 in our program).
82
We need to increase the value of the counter variable in the body of the loop. This is very
important (and mostly forgotten). Failing to do so will result in an infinite loop (never ending
loop).
Finally, the result is displayed.
Let’s Practice
Let’s Go through the flow control Jupyter Notebook to get an experiential learning
experience for ‘for’ and ‘while’ loop . To download the Jupyter Notebook, go to the following
link : http://bit.ly/loops_jupyter
Note:
To open Jupyter notebook, go to start menu open anaconda prompt write “jupyter
notebook”
Test Your Knowledge
Q1) Explain different types of 'If' statements with the help of a flowchart.
Q2) What is the difference between 'for' loop and 'while' loop. Explain with a help of a
flowchart?
Q3) What are python nested if statements? Explain with example.
Q4) Write a program to find numbers which are divisible by 7 and multiple of 5 between 1200
and 2200.
Q5) Write a program to find the whether a number is prime or not using 'while' loop.
83