0% found this document useful (0 votes)
22 views10 pages

Ln. 4 - Lists

This document provides an overview of working with lists and dictionaries in Python, detailing their properties, methods, and operations. It covers list creation, indexing, modification, and various built-in functions such as append, extend, and sort. Additionally, it explains list slicing, membership testing, and deletion methods, along with examples for clarity.

Uploaded by

studynerd247
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views10 pages

Ln. 4 - Lists

This document provides an overview of working with lists and dictionaries in Python, detailing their properties, methods, and operations. It covers list creation, indexing, modification, and various built-in functions such as append, extend, and sort. Additionally, it explains list slicing, membership testing, and deletion methods, along with examples for clarity.

Uploaded by

studynerd247
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Grade 11- IP notes

Lesson 4 – Working with Lists & Dictionary

INTRODUCTION
A list is a standard data type of Python that can store a sequence of values belonging
to any type.
It is a collection which is ordered and changeable.
Elements of a list are enclosed in square brackets and are separated by comma.
The most powerful thing is that list need not be always homogeneous.

Declaring a list
To create a list, put the list elements in square brackets.
Indexing in a list begins from 0

Examples of list-
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ] # list of integers
list3 = ["a", "b", "c", "d"]

Difference- String & Lists


• String is enclosed within ‘ ‘ or “ “ but lists are within [ ].
• Lists can hold any type of data i.e. integers, characters, strings etc, while strings can
only hold a set of characters.
• A string's length is the number of characters in the string; a list's length is the
number of items in the list.
• Strings are not mutable, while lists are mutable.

eval function
• The eval() function evaluates the specified expression, and if the expression is a legal
Python statement, it will be executed.
• It returns the result evaluated from the expression.
• It tries to identify the type by looking at the given expression.

Empty list
• The empty list is [ ]. It is equivalent of 0 or ‘ ‘.
• You can also create an empty list as : L = list( )
• [ ] # list with no member, empty list

Working with list


• Each element in list is accessed using value called index.
• The fist index value is 0, the second index is 1 and so on.
• To access values in lists, use the square brackets along with index whose value is to
be displayed .
>>> ab=[2,4,6,8,10,12]
>>> ab[0] Op- 2
>>> ab[3] O/p- 8
>>> ab[15] O/p- IndexError: list index out of range
>>> ab[1+4] O/p- 12 # 1+4=5 gives 5th index
>>> ab[-1] O/p- 12 # last element

Changing Content of a list


The contents of the list can be changed after it has been created.
Firstlist = ["France", "Belgium", "England"]
Firstlist[2]=“Russia”
This statement will replace England by Russia

Nested list
A list can have an element in it, which itself is a list. Such a list is called nested list.
e.g. L1 = [3, 4 , [5,6], 7]

Creating list from existing sequence


A list from a given sequence(strings, tuples and lists) can be created as per following
syntax:
L = list(<sequence>)

Accessing Individual Elements


The individual elements of a list are accessed through their indexes.
If you give index value outside the legal indices ( 0 to length-1 or –length to -1),
Python will raise Index Error.
Example-
Vowels = [‘a’,’e’,’i’,’o’,’u’]
Vowels[0] → ‘a’
Vowels[-5] → ‘a’
Vowels [5] → Error- list index out of range

Reversing a List
Abc = [5 ,6, 8, 11, 3]
Abc [ : : -1] Output- [3, 11, 8, 6, 5]

Using Slices for list modification


Abc = [“one”, “two”, “THREE”]
Abc[0:2] = [0,1] Output- [0, 1, “THREE”]
>>> A=[1,2,3,4,5,6]
>>> A[0:3]="c"
>>> A Output - ['c', 4, 5, 6]

Comparing Lists
Comparison between lists can be done using standard comparison operators of
Python, i.e. < , > , == , != etc.
For 2 lists to be equal, they must have the same number of elements and matching
values.
In the case of int and float, they will be equal if they have the same matching values
not considering the decimal point.
Example-
L1=[1,2,3]
L2 =[1,2,3]
L3=[4,5,6]
L4=[‘a’,’b’,’c’]
L1==L2 → True
L1==L3 → False
L1==L4 → False

Non equality comparison in list sequences

List operations
The data type list allows manipulation of its contents through various operations like-
Concatentation , Repetition ,Membership, Slicing

Joining Lists By Concatenation


The concatenation operator + , when used with two lists, joins two lists.
The resultant list displays the elements of the 1st list followed by that of the 2nd.
The original list will not change.
A= [ 1,3,5]
B= [ 6,7,8]
A+B O / p → [ 1,3,5,6,7,8]
Note- Both the operands must of list types. The following expressions can result into
an error- List + number , List + string
>>> list1 = [1,2,3]
>>> str1 = "abc"
>>> list1 + str1
TypeError: can only concatenate list (not "str") to list

Repeating or Replicating Lists


Operator is used to replicate a list specified number of times.
A=[1,2,3]
A*2 O/p – [1,2,3,1,2,3]
>>> list1 = ['Hello']
>>> list1 * 4 o/p- ['Hello', 'Hello', 'Hello', 'Hello']

Membership
• The membership operator in checks if the element is present in the list and returns
True, else returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1 → True
>>> 'Cyan' in list1 → False
• The Operator not in returns True if the element is not present in the list, else it
returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Cyan' not in list1 → True
Slicing the Lists
Slicing operations allow us to create new list by taking out elements from an existing
list.
List Slices are the sub part of a list extracted out.
You can use indexes of list elements to create list slices as per following format:
seq = L [start : stop ]
>>> a=[10,12,14,20,22,24,30,32,34]
>>> b=a[0:2]
>>> b O/p - [10, 12]
>>> b=a[0:-1]
>>> b O/p - [10, 12, 14, 20, 22, 24, 30, 32]
>>> b=a[3:-3]
>>> b O/p - [20, 22, 24]
>>> b=a[3:3]
>>> b [] --even if both limits are out of bounds, Python will not give any error and
returns an empty sequence.
a=[20,22,24]
>>> a[1]=28
>>> a O/p - [20, 28, 24]
b=a[2:30]
>>> b O/p - [24]
a=[10,12,14,20,22,24,30,32,34]
>>> b=a[-12:6]
>>> b O/p - [10, 12, 14, 20, 22, 24]

List also support slice steps. That is, if you want to extract, not consecutive but every
other element of the list, there is a way out – the slice steps. The slice steps are used as
per following format: seq = L[start : stop : step]
a=[10,12,14,20,22,24,30,32,34]
a[0:10:2] O/p - [10,14,22,30,34]
a[2:10:3] O/p - [14,24,34]
a[: : 3] O/p - [10,20,30]

List Methods and Built-in Functions


1. len()
Returns the length of the list passed as the argument.
list1 = [10,20,30,40,50]
len(list1)
O/p- 5

2. list()
Creates an empty list if no argument is passed.
>>> list1 = list()
>>> list1 → []
Creates a list if a sequence is passed as an argument.
>>> str1= 'aeiou'
>>> list1 = list(str1)
>>> list1 O/p- ['a', 'e', 'i', 'o', 'u']

3. APPEND
It adds a single item to the end of the list. It doesn’t create a new list but modifies the
original one. It can even add a list of elements at the end, in the form of a list itself.
Syntax is- List.append(item)
e.g : abc= ["apple", "banana", "cherry"]
abc.append(“plum")
list1 = [10,20,30,40]
list1.append([50,60])
list1 → [10, 20, 30, 40, [50, 60]]

4. EXTEND
• The extend( ) method adds one list at the end of the other list.
• All the items of the list are added at the end of an already created list.
• It cannot add a single element; it requires a list to be added.
Syntax is- List.extend(list2)
Eg:- A=[5,3,2,6]
B = [10,11]
A.extend(B)
print (A) O/p- [5,3,2,6,10,11]

5. INSERT
• The insert( ) function inserts an item at a given index.
• It is used as per following syntax:
List.insert(index_number, value)
• Takes two arguments – index of the item to be inserted and the item itself.
T1 = [‘a’,’e’,’u’]
T1.insert(2,’’I’)
T1 → O/p - [‘a’,’e’,’I’,’u’]
• If however, index is less than zero and not equal to any of the valid negative indexes
of the list, the object is prepended, i.e. added in the beginning of list.
T1= [‘a’, ’e’, ’i’ , ‘o’ , ‘u’]
T1.insert (-9, ‘k’)
T1 O/p - [‘k’, ‘a’, ’e’, ’i’ , ‘o’ , ‘u’]

6. count()
• It counts how many times an element has occurred in a list.
• If the given item is not in the list, it returns zero.
Syntax, List.count(<item>)
>>>b=[12,2,13,14,23,32,45,12,56,78,12,65]
>>> b.count(12) → 3
>>>list("WELCOME TO INDIA").count('E') → 2

7. REVERSE
• This function reverses the order of the elements in a list.
• It does not create a new list but replaces a new value in place of the already existing
items.
T1= [‘abc’ , ‘def’ , ‘ghi’ ]
T1.reverse ( )
T1 O/p- [‘ghi’ , ‘def’ , ‘abc’]

8. INDEX
• Returns index of the first occurrence of the element in the list.
• Syntax - List.index (<item>)
• If the element is not present, ValueError is generated.
X = [12,14,15,17,18]
X.index(15) O/p- 2
>>> x=list('PYTHON')
>>> x
['P', 'Y', 'T', 'H', 'O', 'N']
>>> x.index('H') O/p- 3

9. SORT
• It sorts the items of the list in ascending or descending order.
• For strings, sorting is done on the basis of their ASCII values.
• To sort it in the decreasing order use, sort(reverse=True)
a=[10,4,8,20,100,65]
>>> a.sort()
>>> a O/p - [4, 8, 10, 20, 65, 100]
>>> a.sort(reverse=True)
>>> a O/p - [100, 65, 20, 10, 8, 4]

10. sorted()
• It functions the same way as sort().
• But it doesn’t update the original list, instead a new list is created.
>>>list1 = [23,45,11,67,85,56]
>>> list2 = sorted(list1)
>>> list1 O/ p - [23, 45, 11, 67, 85, 56]
>>> list2 O/p- [11, 23, 45, 56, 67, 85]
sorted(list1,reverse=True) O/p - [85, 67, 56, 45, 23, 11]
>>> b=[8,2,12,34,14,56,90,88]
>>> sorted(b)
[2, 8, 12, 14, 34, 56, 88, 90]
>>> b
[8, 2, 12, 34, 14, 56, 90, 88]

DELETION OPERATION
• To delete or remove items from a list, there are many methods used-
✓ Pop() or del () is used in cases the index is known.
✓ Remove() is used if the element is known.
✓ Del() with list slice is used to remove more than one element.

11. CLEAR
• It removes all the items from the list. It doesn’t take any parameters.
• It only empties the given list and does not return any value.
a=[10,4,8,20,100,65]
>>> a.clear()
>>> a O/ p - [ ]

12. REMOVE
• Removes the given element from the list.
• If the element is present multiple times, only the first occurrence is removed.
• If the element is not present, then ValueError is generated
Eg: pqr= ["apple", "banana", "cherry"]
pqr.remove(“cherry”)
['apple', 'banana']
>>> list1 = [10,20,30,40,50,30]
>>> list1.remove(30)
>>> list1 → [10, 20, 40, 50, 30]
>>> list1.remove(90) → ValueError:list.remove(x):x not in list

13. POP
• It removes the element from specified index and returns the element which was
removed.
• An error is shown if the list is already empty.
List.pop(<index>) # index is optional; if skipped, last element is deleted.
X=[1,2,5,4,3,6,7,12,50]
>>> Y=X.pop(2)
>>> X O/p - [1, 2, 4, 3, 6, 7, 12, 50]
>>> Y 5
>>> X.pop() → 50
>>> X O/p - [1, 2, 4, 3, 6, 7, 12]

14. DEL
• It removes the specified element from the list but does not return the deleted value.
• An error is shown if an out of range index is specified with del() and pop().
>>> X [1, 2, 4, 3, 6, 7, 12]
>>> del X[5]
>>> X [1, 2, 4,3, 6, 12]

15. DEL with slicing


• It removes the specified elements from the list identified with the slice operator but
does not return the deleted value.
• If you use del <Listname> only, then it deletes all the elements and the list object
too.
>>>P=[10,20,30,40,50,60,70,80,90]
>>> del P[2:4]
>>> P O/p - [10, 20, 50, 60, 70, 80, 90]
>>> del P
>>> P O/p - Error name 'P' is not defined

16. sum()
• Returns sum of the elements of the list.
• start : This parameter is added to the sum of numbers.
• If start is not given in the syntax , it is assumed to be 0.
>>> s=[10,20,30]
>>> sum(s) O/p- 60
>>> sum(s,10) O/p- 70

17. MAX - It returns the element with the maximum value from the list.
P=[10,20,30,40] max(P) O/p- 40
Q=[‘A’,’a’,’B’,’C’] Max(Q) O/p → a Highest ASCII
value
Q=[‘apple’,’bus’,’shell’]
Max(Q) O/p -shell → Returns the string that starts with the character with highest
ASCII value

18. MIN - It returns the element with the minimum value from the list.
P=[10,20,30,40] min(P) O/p - 10
If there are 2 or more strings that start with the same character, then the second
character is compared and so on.

Traversing a List
Traversal means accessing and processing each element of it.
The for loop makes it easy to traverse or loop over the items in a list, as per following
syntax:
for <item> in <list> :
L=[‘p’,’y’,’t’,’h’,’o’,’n’]
for a in L: p
print (a) y
t Value at index o is q
Traversing a List using index value h
L = [ ‘q’ , ‘w’ , ‘e’ , ‘r’ , ‘t’ , ‘y’ ] Value at index 1 is w
o Value at index 2 is e
Length = len(L) n
for a in range(length) : Value at index 3 is r
Value at index 4 is t
print(“value at index”, a, “is”, L[a])
Value at index 5 is y

PROGRAMS WITH LIST

Program 1 - # Count the number of occurrences of an item in a list


A=eval(input("Enter list: "))
num=eval(input("Enter the number:"))
count=0
for i in A:
if num==i:
count+=1
if count==0:
print("Item is not in list")
else:
print("Count of item - ",count)

Program 2- # To find the sum and average (mean) of a list of items


list1 = eval(input("Enter list: "))
sum = 0
for num in list1:
sum = sum +num
average = sum / len(list1)
print ("sum of list element is : ", sum)
print ("Average of list element is ", average )

Program 3- Find the output of


PQ = [“Mon”,45,”Tue”, 43,”Wed”,42]
[45, 'Tue', 43, 'Wed']
print(PQ [ 1:-1])
['Z', 'Tue', 43, 'Wed', 42]
PQ [0:2] = ‘Z’
print (PQ)

a=[5,10,15,20,25]
k=1
i=a[1]+1
j=a[2]+1 [11 16 15]
m=a[k+1]
print(i,j,m)

L=['p','w','r','d','a']
L.remove('r') ['p', 'w', 'd', 'a']
print(L) a
print(L.pop()) ['p', 'd']
del L[1]
print(L)

L1=[500,600]
L2=[35,45]
L1.append(700)
L1.extend(L2)
[500, 600, 700, 35, 45, 2]
L1.insert(25,2)
[500, 600, 700, 35, 45, 2, 35, 45]
print(L1)
[500, 600, 700, 35, 45, 2]
print(L1+L2)
3
print(L1) [35, 45, 35, 45]
print(L1.index(35))
print(L2*2)

Program 4- What is the for loop for the following output?


1 5
4 for A in range(1,11,3): 4 for B in range(5,0,-1):
7 print(A) 3 print(B)
10 2
1
1 2
3 for C in range(1,8,2): 4 for D in range(2,11,2):
5 print(C) 6 print(D)
7 8
10

Program 5- # To enter a string and count the number of words


A=input("Enter a string :")
B=A.split()
count=0
for i in range(len(B)):
count+=1
print("Number of words : ", count)
Enter a string :The sun rises in the east
Number of words : 6

Program 6- Create an empty list. Fill it up with values. Enter another number to search
for. Use membership operator to search for its existence.

abc =[]
n = int(input("Enter the number of elements in the list:"))
for i in range(0,n):
a=int(input("Enter the item:"))
abc.append(a)
print("The final list is :" , abc)
b=int(input('ENter the number to search for '))
if (b not in abc):
print("b is NOT present in given list")
else:
print("x is present in given list")

Program 7- Write the program to find at least one common element of 2 lists.
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Program 8- To Create two lists with EVEN numbers and ODD numbers from a list
list1 = [11, 22, 33, 44, 55]
odd = []
even = []
for num in list1:
if num%2 == 0:
even.append(num)
else:
odd.append(num)
print ("list1: ", list1 )
print ("listEven: ", even)
print ("listOdd: ", odd)

Question-
Find the output
list1 = [1,2,3,4,5,6,7,8,9,10]
a) list1[::-2] Ans. [1,3,5,7,9]
b) list1[:3] + list1[3:] Ans. [[1,2,3,4,5,6,7,8,9,10]

Question-
Find the object of following questions based on list:
value = [45,32,98, -78, -6, ‘Hello’, ‘Honesty’]
(i) value [5] Ans. ‘Hello’
(ii) value [-5] Ans. 98
(iii) value [1] + value [-1] Ans. TypeError:unsupported operand type (s) for + ‘int’
and ‘str’
(iv) value [4] + value [-4] Ans. -84

You might also like