0% found this document useful (0 votes)
17 views20 pages

CH 9 Lists

This document provides a comprehensive overview of lists in Python, detailing their characteristics, creation, access methods, and various operators. It explains the differences between lists and strings, how to create and manipulate lists, and introduces list methods and built-in functions. Additionally, it covers list operators such as concatenation, repetition, slicing, and membership, along with examples for better understanding.

Uploaded by

ai.crimson158
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)
17 views20 pages

CH 9 Lists

This document provides a comprehensive overview of lists in Python, detailing their characteristics, creation, access methods, and various operators. It explains the differences between lists and strings, how to create and manipulate lists, and introduces list methods and built-in functions. Additionally, it covers list operators such as concatenation, repetition, slicing, and membership, along with examples for better understanding.

Uploaded by

ai.crimson158
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/ 20

CHAPTER-9

LISTS

List is a collection of elements which is ordered and changeable(mutable).

Eg. >>> L1=[200,20.3,’python’]


>>>print(L1)
[200,20.3,’python’]

>>>L2=[‘a’, 12, 1.2]


>>>L2[2]
1.2

Difference between List and String


LIST STRING
Mutable Immutable
Elements can be assigned at specific Elements/characters cannot be
index assigned at specific index
Eg. >>> L1=[1,2,3,4] Eg. >>>Str1=”python”
>>>L1[3]=2 >>>Str1[2]=’P’
>>>print(L1) Syntax Error
[1,2,3,2]
Creating and Accessing Lists

1. Creating Lists
To create a list, enclose the elements in square brackets and separate with commas.

Syntax:

list_name=[item1,item2…….item n]

eg: list1=[1.2.”python”,5]

➢ Empty List- The empty list is [ ].


Eg: list1=[ ]
➢ Nested list: A list inside another list is called nested list.
Eg: L1=[1,’a’,34,[3,6,9],[12,24]]

Creating list by taking input from user

Eg:>>> L1=list{input(“Enter the list elements:”))


Enter the elements:Hello
>>>L1
[‘H’,’e’,’l’,’l’,’o’]

Eg; L2=list(input(“Enter list elements:”))


Enter list elements:234567
>>>L2
[‘2’,’3’,’4’,’5’,’6’,’7’]
In the above example, it created the elements as characters even though we entered digits.
To overcome the above problems we can use eval() method which identifies the datatype and
evaluate them automatically.
L1=eval(input(“Enter the elements:”))
Enter the elements:23456
>>>L1
23456 # it is an integer, not a list
>>>L2=eval(input(“Enter the elements:”))
Enter the elements:[1,’a’,3,5,’python’]
>>>L2
[1,’a’,3,5,’python’]
NOTE:- With eval() method, if you enter elements without brackets [ ], it will be considered as a
tuple.

Eg:>>> L1=eval(input(“Enter the elements:”))


Enter the elements: 2, 4 ‘python’,6, ‘p’
>>> L1
(2,4, ‘python’,6,’p’) # it is a tuple

2. Accessing Lists
The values stored in a list can be accessed using the slice operator ([ ],[:]) with indexes.
List_name[start:end] will give you the elements between indices start and end.
Eg. L1=[1,2,3,4,5]

>>>L1[3]
4
>>>L1[8]
Index error: List index out of range
>>>L1[-3]
3
>>>L1[2]=6 # assigning value
>>>L1
[1,2,6,4,5]

Traversing a list
Traversal of list means accessing and processing each element of it.
❖ Using for loop

Syntax:

for <item> in <List>:


process each item

eg: L=[‘p’,’y’,’t’,’h’,’o’,’n’]
for a in L:
print(a)

Output:
P
y
t
h
o
n

eg: >>>d=list(input(“Enter the elements:”))


>>>for a in d:
print(a)

Output:
Enter the elements: Monday
M
o
n
d
a
y

Eg. >>>for a in range (len(d))


Print (a[:])
Output:

M
o
n
d
a
y
❖ Using while loop
>>>d=list(input(“Enter the elements:”))
Enter the elements: Monday

>>>i=0

while i<len(d):

print(d[i])

i+=1

Output:
M
o
n
d
a
y
List Operators
1. Concatenation operator(+)
2. Repetition Operator (*)
3. Slice Operator([ ] and [:])
4. Relational Operator (<, <=,>, >=.!=,==)
5. Membership Operator(in and not in)

1. Concatenation Operator or Joining Operator (+)


It is used for joining two or more lists.
Eg. >>>L1=[1,2,3.8]
>>>L2=[“python”]
>>>L3=[‘a’,’b’]
>>>L1+L2+L3
[1,2,3.8,”python”,’a’,’b’]
2. Repetition Operator
It replicates a list with specified number of times.
Eg. >>>L1=[1,3,5]
>>>L1*3
[1,3,5,1,3,5,1,3,5]

3. Slice Operator
a. List_name[start,stop]
This syntax will create a list having elements of list on indexes from start to stop-1.
Eg. >>>L1=[12,56,87,45,23,97,56,27]
>>>L1[2:-2]
[87,45,23,97]

>>>L1[4:20] # Second index is out of range list


[23,97,56,27] stops at the end of list
>>>L1 [ - 6:- 1]

[87,45,23,97,56]

>>>L1[-1:-6] -1 > -6

[] # empty list

>>>L1[0:len(L1)]

[12,56,87,45,23,97,56,27]

b. list_name [start:end:step]
This syntax will give you elements between indices from start to end – 1
with skipping elements as per the value of step.

Eg: >>>L1 [1:6:2]

[56,45,97]

>>>L1[:: - 1] # reversing list

[27,56,97,23,45,87,56,12]

c. List modification using slice operator : [skip some values]

Eg. >>>L1 [2:4] = [“hello”, “python ”]

>>>L1

[12,56 “hello”, “python”,23,97,56,27]

Eg. >>>L1[2:4]=[“computer”]

>>>L1
12.56,” computer”,23,97,56,27]

The values being assigned must be a sequence i.e, a list or string or tuple etc.

Eg. >>>L1=[1,2,3]

>>>L1[2:]=”604” # string is also a sequence

>>>L1

[1,2,’6’,’0’,’4’]

>>>L1[2:]=345 # 345 is a number, not a sequence

Type Error: can only assign an iterable

>>>L1[1:3]=[345]

>>>L1

[1,345]

>>>L1[10:20]=”abcd” # no error though list slice limits are outside the length

[1,2,3,’a’,’b’,’c’] Now Python will append the letters at the end

4. Relational Operator: Compares two lists


• Python internally compares individual elements list individual elements of list
in lexicographical order.
• It compares each corresponding element which must be compared with
sequence and equality of same type.
• For non-equal comparison , the result will be True or False for corresponding
elements comparison. If corresponding elements are equal it goes to the next
element and so on until it finds the difference.
Eg. >>> L1,L2=[1,2,3],[1,2,3]
>>>L3= [1,[2,3]]
For equal comparison – [==,!=]

Eg.>>> L1==L2

True # corresponding elements have same values


>>>L1==L3
False # corresponding elements are not same
For non-equal comparison- [<,>]
Eg. >>>L1>L2
False # All elements are same
>>> L2>L3
Type error: ‘>’ not supported between instances of int and list
# In L2, element at index I is int and in L3 element at index 1 is list
>>>[3,4,7,8] <[5,1]

True # 3<5 is True


>>> [3,4,7,8] < [3,4,9,2]
True # 7<9 first two elements are same
>>>[3,4,7,8] < [3,4,9,11]
True # 7<9-True
>>>[3,4,7,8] < [3,4,7,5]
False # 8>5
5. Membership Operators- Checks if the element is present in a list and returns true,
else returns false.

Eg. >>>L1=[10,20,30,40]
>>> 20 in L1
True
>>> 50 in L1
False
>>>20 not in L1
False
>>>60 not in L1
True

List methods & Built in Functions


1. len()
Syntax: len(list_name)
It returns the length of the list passed as an argument.
Eg. >>>L1=[1,2,3,4,5]
>>>len(L1)
5
2. list()
Syntax: list()
Creates a list if a sequence is passed as an argument

Eg. >>> list1 = list()


>>> list1
[]
Creates a list if a sequence is passed as an argument
>>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', ’o’ ,’u’]
3. append()
Syntax: list_name(element)
Appends a single element passed as an argument at the end of the list The single element can
also be a list
>>> list1 = [10,20,30,40]
>>> list1.append(50)
>>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40]
>>> list1.append([50,60])
>>> list1
[10, 20, 30, 40, [50, 60]]
4. extend()
Syntax: list_name_extend(list)
Appends each element of the list passed as argument to the end of the given list
>>> list1 = [10,20,30]
>>> list2 = [40,50]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]
5. insert()
Syntax: list_name.insert(index,element)
Inserts an element at a particular index in the list
>>> list1 = [10,20,30,40,50]
>>> list1.insert(2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]
6. count()
Syntax: list_name.count(element)
Returns the number of times a given element appears in the list
>>> list1 = [10,20,30,10,40,10]
>>> list1.count(10)
3
>>> list1.count(90)
0

7. index()
syntax: listname.index(element)

Returns index of the first occurrence of the element in the list. If the element is not present,

ValueError is generated

>>> list1 = [10,20,30,20,40,10]

>>> list1.index(20)

>>> list1.index(90)

ValueError: 90 is not in list

8. remove()

Syntax: list_name.remove(element)

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

>>> 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

9. pop()

Syntax: list_name.pop(index)
Returns the element whose index is passed as parameter to this function and also removes it from the

list. If no parameter is given, then it returns and removes the last element of the list

>>> list1 = [10,20,30,40,50,60]

>>> list1.pop(3)

40

>>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop()
60
10. reverse()

Syntax: list_name.reverse()

Reverses the order of elements in the given list

>>> list1 = [34,66,12,89,28,99]

>>> list1.reverse()

>>> list1

[ 99, 28, 89, 12, 66, 34]

>>> list1 = [ 'Tiger' ,'Zebra' ,

'Lion' , 'Cat' ,'Elephant' ,'Dog']

>>> list1.reverse()

>>> list1

['Dog', 'Elephant', 'Cat',

'Lion', 'Zebra', 'Tiger']

11. del statement

Syntax: del list_name[index] or del List_name[start:stop]


The del statement can be used to delete an item at a given index. It can also be used to

remove slices from a list.

>>>L1=[10,20,30,40,50]

>>>del L1[2]

>>>L1

[10,20,40,50]

>>>del L1[0:3]

>>>L1

[50]

>>>del L1

>>>L1

Name error :L1 not defined

Note: Whereas pop() and remove() provide empty list([ ]) after all the elements are removed or

popped out.

12. sort()

Syntax: List_name.sort()

Sorts the elements of the given list in-place (by default: Ascending order)

>>>list1 = ['Tiger','Zebra','Lion',

'Cat', 'Elephant' ,'Dog']

>>> list1.sort()

>>> list1

['Cat', 'Dog', 'Elephant', 'Lion',

'Tiger', 'Zebra']
>>> list1 = [34,66,12,89,28,99]

>>> list1.sort(reverse = True) # to print in descending order

>>> list1

[99,89,66,34,28,12]

13. sorted()

Syntax: sorted(list_name)

It takes a list as parameter and creates a new list consisting of the same elements arranged in

sorted order

>>> list1 = [23,45,11,67,85,56]

>>> list2 = sorted(list1)

>>> list1

[23, 45, 11, 67, 85, 56]

>>> list2

[11, 23, 45, 56, 67, 85]

14. min()

syntax: min(list_name)

Returns minimum or smallest element of the list

>>> list1 = [34,12,63,39,92,44]

>>> min(list1)

12

15. max()

Syntax: max(list_name()

Returns maximum or largest element of the list

>>> list1 = [34,12,63,39,92,44]


>>> max(list1)

92

16. sum()

Syntax: sum(list_name)

Returns sum of the elements of the list

>>> list1 = [34,12,63,39,92,44]

>>> sum(list1)

284

Nested List
>>> list1 = [1,2,'a','c',[6,7,8],4,9] #fifth element of list is also a list
>>> list1[4]
[6, 7, 8]
To access the element of the nested list of list1, we have to specify two indices

Syntax: list1[i][j]

The first index i will take us to the desired nested list and second index j will take us to the
desired element in that nested list.
Eg. >>> list1[4][1]
7

Copying List
Simplest way to copy list is to assign it to another list.
Eg; >>>L1=[1,2,3]
>>>L2=L1
>>>L2
[1,2,3]
If any change made to L1 will reflect in L2 also. Therefore, any changes made to any of the lists
will reflect in both lists.
>>>L1[2]=4
>>>L1
[1,2,4]
>>>L2
[1,2,4]
>>>L2[1]=0
>>>L1
[1,0,4]

Create a copy or clone of the list as a distinct object by three methods


Method 1 : We can use the built in function copy () as follows:
Syntax:
import copy
newList = copy.copy(oldList)
eg. >>> import copy
>>> L1 = [1,2,3,4,5]
>>> L2 = copy.copy(L1)
>>> L2
[1, 2, 3, 4, 5]

Method 2 : Using Slice operator

Syntax:
newList = oldList[:]
eg. >>>L1=[10,20,30]
>>>L2=L1[ : ]
>>>L2
[10,20,30]

Method 3: using built in function list()

Syntax: newList = list(oldList)

Eg: >>> L1 = [10,20,30,40]

>>> L2 = list(L1)
>>> L2
[10, 20, 30, 40]
Programs in List
1. Write a program to find the largest / smallest number in a list.
L = eval(input("Enter the list: "))
Largest = L[0]
Lindex = 0
for i in range(len(L)):
if L[i] > Largest:
Largest = L[i]
Lindex = i
print("The largest number =", Largest, "at index =", Lindex)
OUTPUT:
Enter the list: [12, 45, 23, 89, 34, 23]
The largest number = 89 at index = 3

2. Write a program to find the largest and smallest number in a list


L = eval(input("Enter the list: "))
Largest = Smallest=L[0]
Lindex =Sindex=0
for i in range(len(L)):
if L[i] > Largest:
Largest = L[i]
Lindex = i
elif L[i]<Smallest:
Smallest=L[i]
Sindex=i
print("The largest number =", Largest, "at index =", Lindex)
print("The smallest number =", Smallest, "at index =", Sindex)
OUTPUT:
Enter the list= [12, 45, 23, 89, 34, 23]
The largest number = 89 at index = 3
The smallest number=12 at index=0

3. Write a program to find the second largest element in a list.


L = eval(input("Enter the list: "))
Largest = SLargest = L[0]
for i in range(len(L)):
if L[i] > Largest:
SLargest = Largest
Largest = L[i]
elif L[i] > SLargest and L[i] != Largest:
SLargest = L[i]

print("Second largest number in the list =", SLargest)

OUTPUT:
Enter the list: [23, 78, 45, 12, 90, 67]
Second largest number in the list = 78

4. Write a program to find the sum, mean of list elements.


L = eval(input("Enter the list elements: "))
Length = len(L)
Sum = 0
for i in range(Length):
Sum += L[i]
Mean = Sum / Length
print("Sum of the elements =", Sum)
print("Mean =", Mean)
OUTPUT:
Enter the list elements: [1, 2, 3, 4, 5]
Sum of the elements = 15
Mean = 3.0

5. WAP to input a list of numbers and swap elements at the even location with the
elements at odd location.
L=eval(input(“Enter the list elements:”))
for I in range(0,len(L),2):
L[i], L[i+1]=L[i+1],L[i]
print(“The swapped list:”,L)
OUTPUT:
Enter the list elements: [1, 2, 3, 4, 5]
The swapped list: [2, 1, 4, 3, 5]

6. Write a program to input a list of elements, search for a given element in the list.
L = eval(input("Enter the list: "))
val = int(input("Enter the element to be searched: "))
for i in range(len(L)):
if val == L[i]:
print(val, "found at index", i)
break
else:
print(val, "not found in given list")
OUTPUT:
Enter the list: [10, 20, 30, 40, 50]
Enter the element to be searched: 30
30 found at index

******************************

You might also like