0% found this document useful (0 votes)
16 views

Unit 2 Chapter-4 Lists

Uploaded by

firegamers419
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Unit 2 Chapter-4 Lists

Uploaded by

firegamers419
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Unit 2

Chapter - 4
Lists

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
Introduction
Sequence in an object that contain multiple items of
data.

A sequence may have repeated items in the list. The


number of elements are called length of the sequence.

Sequences in Python
Lists, Dictionaries, Strings, Tuples and Sets

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
Introduction
The data type list is an ordered sequence which
is mutable and made up of one or more elements.

Unlike a string which consists of only characters, a


list can have elements of different data types
such as integer, float, string, tuple or even another
list.

A list is very useful to group elements of mixed


data types. Elements of a list are enclosed in
square brackets and are separated by comma.

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
1. Lists
A list is a collection of items and each item has its own
index value. The items in a list can be of any type such
as strings, integers, floats.

Items in a list can be of multiple types. The


items/elements are enclosed in Square brackets [ ].

Index of first item is 0 and the last item is n-1.


Here n is number of items in a list.

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
a. Creating a List
The syntax for creating a list is:
<list_name> = [ ]

Creating a list
Lists are enclosed in square brackets [ ] and
each item is separated by a comma.

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
Creating a List (e.g.)
#list1 is the list of six even numbers
>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]

#list2 is the list of vowels


>>> list2 = ['a','e','i','o','u']
>>> print(list2)
['a', 'e', 'i', 'o', 'u’]

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
Creating a List (e.g.)
#list3 is the list of mixed data types
>>> list3 = [100,23.5,'Hello']
>>> print(list3)
[100, 23.5, 'Hello’]

#list4 is the list of lists called nested list


>>> list4 =[['Physics',101],['Chemistry',202], ['Mathematics',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202],['Mathematics', 303]]

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
b. Initilaizing a List
#initialing a list named list1
>>> list1 = [2,4,6,8,10,12]

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
c. Accessing Elements in a List
Each element in list is accessed using value called
index.

The first index value is 0, the second index is 1 and


so on.
Elements in the list are assigned index values in
increasing order sterling from 0.

To access an element, use square brackets with the


index [] value of that element.

We may also use negative index value to access


elements starting from the last element in the list,
having index value -1.
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
c. Accessing Elements in a List
>>> list1 = [2,4,6,8,10,12]

>>> list1[0] #returns first element of list1


2

>>> list1[3] #returns fourth element of list1


8

#Out of range index value for the list returns error


>>> list1[15]
IndexError: list index out of range

#an expression resulting in an integer index


>>> list1[1+4]
12
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
Accessing Elements in a List
>>> list1 = [2,4,6,8,10,12]

>>> list1[-1] #return first element from right


12

#length of the list1 is assigned to n


>>> n = len(list1)
>>> print(n)
6

#Get the last element of the list1


>>> list1[n-1]
12

#Get the first element of list1


>>> list1[-n]
2
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
Accessing Elements in a List

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
Lists are Mutable
Lists are Mutable

In Python, lists are mutable. It means that the contents of


the list can be changed after it has been created.

#List list1 of colors


>>> list1 = ['Red','Green','Blue','Orange’]

#change/override the fourth element of list1


>>> list1[3] = 'Black’

>>> list1 #print the modified list list1


['Red', 'Green', 'Blue', 'Black']

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
d. Travesing a List
Traversing means accessing each item in the list.
This can be done using loops (for or while)

(A) List traversal using for loop:

list1 = ['Red','Green','Blue','Yellow', 'Black']


for item in list1:
print(item)

Output:
Red
Green
Blue
Yellow
Black

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
Travesing a List
(B) Another way of accessing the elements of the list is using range() and
len() functions:

list1 = ['Red','Green','Blue','Yellow', 'Black']

for i in range(len(list1)):
print(list1[i])

Output:
Red
Green
Blue
Yellow
Black

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
List methods and built in Functions
List Methods and Built-in Functions
The data type list has several built-in methods that are useful in
programming.

Courtesy: NCERT
List methods and built in Functions

Courtesy: NCERT
List methods and built in Functions

Courtesy: NCERT
List methods and built in Functions

Courtesy: NCERT
List methods and built in Functions

Courtesy: NCERT
List methods and built in Functions

Courtesy: NCERT
Manipulating a List
Various list manipulation methods are:

1. Append an element
2. Insert an element
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element from its position
6. Delete an existing element with a given value
7. Sort the list in the ascending order
8. Sort the list in descending order
9. Display the list.

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
Manipulating a List
myList=[22,4,16,38,13] #myList having 5 elements

1. Append an element

element = eval(input("Enter the element to be appended: "))


myList.append(element)
print("The element has been appended")

2. Insert an element

element = eval(input("Enter the element to be inserted: "))


pos = int(input("Enter the position:"))
myList.insert(pos, element)
print("The element has been inserted")

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
Manipulating a List
3. Append a list to the given list

newList=eval(input("Enter the list to be appended: "))


myList.extend(newList)
print("The list has been appended")

4. Modify an existing element


myList=[22,4,16,38,13]
i = int(input("Enter the position of the element to be modified:
"))
if i < len(myList):
newElement = eval(input("Enter the new element: "))
myList[i] = newElement
print("The element has been modified")
else:
print("Position of the element is more then the length of
list")
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
Manipulating a List
5. Delete an existing element from its position
myList=[22,4,16,38,13]
i = int(input("Enter the position of the element to be deleted:
"))
if i < len(myList):
element = myList.pop(i)
print("The element", element, " has been deleted")
else:
print("Position of the element is more then the length
of list")

6. Delete an existing element with a given value


element = int(input("Enter the element to be deleted: "))
if element in myList:
myList.remove(element)
print("The element", element, " has been deleted")
else:
print("Element", element, " is not present in the list")
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
Manipulating a List
7. Sort the list in the ascending order
myList.sort()
print("The list has been sorted")

8. Sort the list in descending order


myList.sort(reverse = True)
print("The list has been sorted in reverse order")

9. Display the list.


print("The list is:", myList)

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
Operations on Lists
Python provides several basic operations
which can be performed on a list.

a. Slicing
b. Concatenation
c. Repetition
d. Membership testing
e. Indexing

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
a. Slicing
Slicing is an operation in which you can slice a
particular range from that sequence.

List slices are the sub-parts of a list extracted out.

List slices can be created through the use of


indexes.

Syntax:
list[start:stop:step]
start is the starting point.
stop is the stopping point, which is not included.
Step is the step size. It is optional. Default value is 1.
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
a. Slicing
list =['I','N','D','I','A']

print(list[:]) ['I', 'N', 'D', 'I', 'A']


print(list[0:3]) ['I', 'N', 'D']
print(list[2:]) ['D', 'I', 'A']
print(list[:3]) ['I', 'N', 'D']
print(list[-3:]) ['D', 'I', 'A']
print(list[:-4]) ['I']
Print(list[1:4:2]) [‘N‘,'I']
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
a. Slicing
Consider a list/sequence as:

>>> x='computer'
>>> x[1:4] # omp
>>> x[3:] # puter
>>> x[:5] # compu
>>> x[-3:] # ter
>>> x[:-2] # comput

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
a. Slicing
>>> list1 =['Red','Green','Blue','Cyan','Magenta','Yellow','Black’]

#subject from indexes 2 to 5 of list1


>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow’]

#list1 is truncated to the end of the list


>>> list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black’]

>>> list1[7:2] #first index > second index


[] #results in an empty list

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
a. Slicing
>>> list1 =['Red','Green','Blue','Cyan','Magenta','Yellow','Black’]

#return sublist from index 0 to 4


>>> list1[:5] #first index missing
['Red','Green','Blue','Cyan','Magenta’]

#slicing with a given step size


>>> list1[0:6:2]
['Red','Blue','Magenta’]

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
a. Slicing
>>> list1 =['Red','Green','Blue','Cyan','Magenta','Yellow','Black’]

#negative indexes
#elements at index -6,-5,-4,-3 are sliced
>>> list1[-6:-2]
['Green','Blue','Cyan','Magenta’]

#both first and last index missing


>>> list1[::2] #step size 2 on entire list
['Red','Blue','Magenta','Black’]

#Access list in the reverse order using negative step size


>>> list1[::-1]
['Black','Yellow','Magenta','Cyan','Blue', 'Green','Red’]

>>> list1[::-2]
['Black', 'Magenta', 'Blue', 'Red']
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
b. Concatenation
Multiple sequences/lists can be combined together with help
of certain operators.
Python allows adding two lists using ‘+’ operator.

list1=['Red','Green']
list2=[10,20]

list1=list1+['Blue’]
print(list1) #['Red', 'Green', 'Blue']

list2=list2+[30]
print(list2) #[10, 20, 30]

list3=list1+list2
print(list3) #['Red', 'Green', 'Blue', 10, 20, 30]
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
b. Concatenation
>>> list1 = [1,2,3]
>>> str1 = "abc"
>>> list1 + str1
TypeError: can only concatenate list
(not "str") to list

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
c. Repetition/Replication
Asterisk (*) operator replicated the List for a
specified number of times.
e.g.
list2=[10,20,30]
print(list2*2) Output: [10, 20, 30, 10, 20, 30]

x="Python"*3
print(x) Output: PythonPythonPython

list1 = ['Hello’] #elements of list1 repeated 4


times
list1 * 4 Output: ['Hello', 'Hello', 'Hello', 'Hello']
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
d. Membership Testing
The Operator in checks if the element is present in
the list and returns True, else returns False.

e.g.1
x='Python'
print ('o' in x)
Output: True

e.g.2
y=[10,20,30,40]
print (50 in y)
Output: False
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
d. Membership Testing
The Operator not in transpose returns True
if the element is not present in the list, else it
returns False.

>>> list1 = ['Red','Green','Blue']


>>> 'Cyan' not in list1
True

>>> 'Green' not in list1


False
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
e. Indexing
Index is a number specifying the position of an
element in a list. It enables access to individual
elements in the list.

e.g.1
list1=['Red','Green','Blue']
list2=[10,20,30]
Output:
print(list1[-1]) Blue
print(list2[2]) 30

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
SUMMARY

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
# Python Program to add items in the list according to
input by user

L=[]
n=int(input("How many items to be entered:"))
i=1
while(i<=n):
a=int(input("Enter element:"))
L.append(a)
i=i+1
print(L)

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
# Python Program to find Largest and Smallest Number in a
List

NumList = [1,33,22,88,4,44]

Number=len(NumList)
print("Length of this List is : ", Number)
smallest = largest = NumList[0]

for i in range(1, Number):

if(smallest > NumList[i]):


smallest = NumList[i]

if(largest < NumList[i]):


largest = NumList[i]

print("The List is:",NumList)


print("The Smallest Element in this List is : ", smallest)
print("The Largest Element in this List is : ", largest)
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt
# Python Program to count occurrence of a Number in the List

ctr=0
List = [1,33,22,88,1,4,44,1]
print(List)
num=int(input("Enter Number in the List:"))

for i in range(0, len(List)):

if(num= =List[i]):
ctr=ctr+1

print("Number of times element occurring in List is:",ctr)

Designed by: Umesh Pun (PGT IP)


APS Yol Cantt
# Python Program to calculate mean of elements in the List

L=[]
n=int(input("How many items to be enetered:"))
i=1
while(i<=n):
a=int(input("Enter element:"))
L.append(a)
i=i+1

sum=0
for i in range(0, len(L)):
sum=sum+L[i]
avg=sum/n

print("The List is",L)


print("The Mean
Designed by: Umesh
APS Yol Cantt
of
Pun (PGT IP)the List is",avg)
# Python Program to perform linear search in a List

L=[10,30,88,27,93]
print(L)
n=int(input("Enter item to be search:"))

flag=0
for i in range(0, len(L)):
if (n==L[i]):
flag=1
break

if (flag==1):
print("Element found")
else:
print("Element not found")
Designed by: Umesh Pun (PGT IP)
APS Yol Cantt

You might also like