[go: up one dir, main page]

0% found this document useful (0 votes)
37 views16 pages

Wa0018.

The document provides information about list manipulation in Python. It defines what a list is, provides examples of creating and accessing list elements, and describes various list methods and operations like slicing, sorting, appending, etc. It also discusses passing lists to functions and how lists are mutable.

Uploaded by

skanupbossgaming
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)
37 views16 pages

Wa0018.

The document provides information about list manipulation in Python. It defines what a list is, provides examples of creating and accessing list elements, and describes various list methods and operations like slicing, sorting, appending, etc. It also discusses passing lists to functions and how lists are mutable.

Uploaded by

skanupbossgaming
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/ 16

DAV SDPS PUBLIC SCHOOL, BHADRAK

List Manipulation in Python


Introduction to List
In Python, Multiple values (example, Number, Character, Date etc.) can be
stored in a single variable by using lists., a list is an ordered sequence of
elements that can be changed or modified. A list’s items are any elements or
values that are contained within it. Lists are defined by having values inside
square brackets [] just as strings are defined by characters inside quotations.

Example 1 –
>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]
Example 2 –
>>> list2 = [‘a’,’e’,’i’,’o’,’u’]
>>> print(list2)
[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
Example 3 –
>>> list3 = [100,23.5,’Hello’]
>>> print(list3)
[100, 23.5, ‘Hello’]

Accessing Elements in a List (Display Element from the List)

The elements of a list are accessed in the same way as characters are
accessed in a string.

Example –

>>> list1 = [2,4,6,8,10,12]


>>> list1[0]
2
>>> list1[3]
8
>>> list1[15]
IndexError: list index out of range

Lists are Mutable

In Python, lists are mutable. It means that the contents of the list can be
changed after it has been created.
Example –

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


>>> list1[3] = ‘Black’
>>> list1
[‘Red’, ‘Green’, ‘Blue’, ‘Black’]

List Operations

The data type list allows manipulation of its contents through various
operations as shown below.

Concatenation

Python allows us to join two or more lists using concatenation operator


depicted by the symbol +.

Example 1 –
>>> list1 = [1,3,5,7,9]
>>> list2 = [2,4,6,8,10]
>>> list1 + list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

Example 2 –
>>> list3 = [‘Red’,’Green’,’Blue’]
>>> list4 = [‘Cyan’, ‘Magenta’, ‘Yellow’ ,’Black’]
>>> list3 + list4
[‘Red’,’Green’,’Blue’,’Cyan’,’Magenta’, ‘Yellow’,’Black’]

Repetition

Python allows us to replicate a list using repetition operator depicted by


symbol *.

>>> list1 = [‘Hello’]


>>> list1 * 4
[‘Hello’, ‘Hello’, ‘Hello’, ‘Hello’]

Membership

Like strings, the membership operators 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

Slicing

Like strings, the slicing operation can also be applied to lists.

Example 1 –
>>> list1 =[‘Red’,’Green’,’Blue’,’Cyan’, ‘Magenta’,’Yellow’,’Black’]
>>> list1[2:6]
[‘Blue’, ‘Cyan’, ‘Magenta’, ‘Yellow’]

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

Traversing a List

We can access each element of the list or traverse a list using a for loop or a
while loop.

List Traversal Using for Loop –

Example –
>>> list1 = [‘Red’,’Green’,’Blue’,’Yellow’, ‘Black’]
>>> for item in list1:
print(item)

Output:
Red
Green
Blue
Yellow
Black

List Traversal Using while Loop –

Example –
>>> list1 = [‘Red’,’Green’,’Blue’,’Yellow’, ‘Black’]
>>> i = 0
>>> while i < len(list1):
print(list1[i])
i += 1
Output:
Red
Green
Blue
Yellow
Black

List Methods and Built-in Functions

The data type list has several built-in methods that are useful in programming.

len()

Returns the length of the list passed as the argument

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


>>> len(list1)
5

list()

Creates an empty list if no argument is passed Creates a list if a sequence is


passed as an argument

Example –
>>> list1 = list()
>>> list1
[]
>>> str1 = ‘aeiou’
>>> list1 = list(str1)
>>> list1
[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

append()

Appends a single element passed as an argument at the end of the list. The
single element can also be a list.

Example –
>>> 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]]

extend()

Appends each element of the list passed as argument to the end of the given
list.

Example –
>>> list1 = [10,20,30]
>>> list2 = [40,50]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]

insert()

Inserts an element at a particular index in the list

Example –
>>> 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]

count()

Returns the number of times a given element appears in the list

Example –
>>> list1 = [10,20,30,10,40,10]
>>> list1.count(10)
3
>>> list1.count(90)
0

index()

Returns index of the first occurrence of the element in the list. If the element
is not present, ValueError is generated.
Example –
>>> list1 = [10,20,30,20,40,10]
>>> list1.index(20)
1
>>> list1.index(90)
ValueError: 90 is not in list

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.

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

pop()

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.

Example –
>>> 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
>>> list1
[10, 20, 30, 40, 50]

reverse()

Reverses the order of elements in the given list

Example –
>>> 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’]

sort()

Sorts the elements of the given list in-place

Example –
>>>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)
>>> list1
[99,89,66,34,28,12]

sorted()

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

Example –
>>> list1 = [23,45,11,67,85,56]
>>> list2 = sorted(list1)
>>> list1
[23, 45, 11, 67, 85, 56]
>>> list2
[11, 23, 45, 56, 67, 85]

min()

Returns minimum or smallest element of the list

Example –
>>> list1 = [34,12,63,39,92,44]
>>> min(list1)
12

max()
Returns maximum or largest element of the list

Example –
>>> list1 = [34,12,63,39,92,44]
>>> max(list1)
92

sum()

Returns sum of the elements of the list

Example –
>>> list1 = [34,12,63,39,92,44]
>>> sum(list1)
284

Nested Lists

When a list appears as an element of another list, it is called a nested list.

Example –
>>> list1 = [1,2,’a’,’c’,[6,7,8],4,9]
>>> list1[4]
[6, 7, 8]

Copying Lists

The simplest way to make a copy of the list is to assign it to another list.

Example –
>>> list1 = [1,2,3]
>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]

List as Argument to a Function

Whenever a list is passed as an argument to a function, we have to consider


two scenarios:

(A) A modification to the list in the function will be mirrored back in the calling
function, which allows for changes to the original list’s elements.
Q. Program to increment the elements of a list. The list is passed as an
argument to a function.

#Program
#Function to increment the elements of the list passed as argument
def increment(list2):
for i in range(0,len(list2)):
list2[i] += 5
print(‘Reference of list Inside Function’,id(list2))
list1 = [10,20,30,40,50]
print(“Reference of list in Main”,id(list1))
print(“The list before the function call”)
print(list1)
increment(list1)
print(“The list after the function call”)
print(list1)

Output:
Reference of list in Main 70615968
The list before the function call
[10, 20, 30, 40, 50]
Reference of list Inside Function 70615968
The list after the function call
[15, 25, 35, 45, 55]

(B) If the list is given a new value inside the function, a new list object is
generated and it becomes the local copy of the function. Any updates made
inside the local copy of the function are not updated in the calling function.

Q. Program to increment the elements of the list passed as parameter.

#Program
#Function to increment the elements of the list passed as argument
def increment(list2):
print(“\nID of list inside function before assignment:”, id(list2))
list2 = [15,25,35,45,55]
print(“ID of list changes inside function after assignment:”, id(list2))
print(“The list inside the function after assignment is:”)
print(list2)
list1 = [10,20,30,40,50]
print(“ID of list before function call:”,id(list1))
print(“The list before function call:”)
print(list1)
increment(list1) #list1 passed as parameter to function
print(‘\nID of list after function call:’,id(list1))
print(“The list after the function call:”)
print(list1)

Output:
ID of list before function call: 65565640
The list before function call:
[10, 20, 30, 40, 50]
ID of list inside function before assignment:65565640
ID of list changes inside function after assignment:65565600
The list inside the function after assignment is:
[15, 25, 35, 45, 55]
ID of list after function call: 65565640
The list after the function call:
[10, 20, 30, 40, 50]

Questions and Answers


1. What will be the output of the following statements?
i. list1 = [12,32,65,26,80,10]
list1.sort()
print(list1)
Answer – [10, 12, 26, 32, 65, 80]

ii. list1 = [12,32,65,26,80,10]


sorted(list1)
print(list1)
Answer – [12, 32, 65, 26, 80, 10]

iii. list1 = [1,2,3,4,5,6,7,8,9,10]


list1[::-2]
print(list1[:3] + list1[3:])
Answer – [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

iv. list1 = [1,2,3,4,5]


print(list1[len(list1)-1])
Answer – 5

2. Consider the following list myList. What will be the elements of myList
after the following two operations:
myList = [10,20,30,40]
i. myList.append([50,60])
print(myList)
Answer – [10, 20, 30, 40, [50, 60]]
ii. myList.extend([80,90])
print(myList)
Answer – [10, 20, 30, 40, 80, 90]

3. What will be the output of the following code segment:


myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len(myList)):
if i%2 == 0:
print(myList[i])
Answer –
1
3
5
7
9

4. What will be the output of the following code segment:


a. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
Answer – [1, 2, 3]

b. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)
Answer – [6, 7, 8, 9, 10]

c. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[::2]
print(myList)
Answer – [2, 4, 6, 8, 10]

5. Differentiate between append() and extend() functions of list.


Answer – append() function helps to adds a single element to the end of the
list, extend() function can add multiple elements to the end of list.

6. Consider a list:
list1 = [6,7,8,9]
What is the difference between the following operations on list1:
a. list1 * 2
b. list1 *= 2
c. list1 = list1 * 2
Answer –
1. The first line of the statement prints each element of the list twice, as in [6,
7, 8, 9, 6, 7, 8, 9]. List1, however, won’t be changed.
2. List1 will be modified and the list with repeated elements, [6, 7, 8, 9, 6, 7, 8,
9], will be assigned to List1.
3. This assertion will similarly have the same outcome as the assertion “list1
*= 2.” List1 will be given the list with the repeated elements, [6, 7, 8, 9, 6, 7, 8, 9].

7. The record of a student (Name, Roll No., Marks in five subjects and
percentage of marks) is stored in the following list:
stRecord = [‘Raman’,’A-36′,[56,98,99,72,69],78.8]
Write Python statements to retrieve the following information from the list
stRecord.
a) Percentage of the student
Answer – stRecord[3]

b) Marks in the fifth subject


Answer –
stRecord[2][4]

c) Maximum marks of the student


Answer –
max(stRecord[2])

d) Roll no. of the student


Answer –
stRecord[1]

e) Change the name of the student from ‘Raman’ to ‘Raghav’


Answer –
stRecord[0] = “Raghav”

1. Write a program to find the number of times an element occurs in the list.
Answer –
list1 = [10, 20, 30, 40, 50, 60, 20, 50]
print(“List is:”,list1)
new_list = int(input(“Enter element Which you like to count? “))
counter = list1.count(new_list)
print(“Count of Element”,new_list,”in the list is:”,counter)

Output
List is: [10, 20, 30, 40, 50, 60, 20, 50]
Enter element Which you like to count? 10
Count of Element 10 in the list is: 1

2. Write a program to read a list of n integers (positive as well as negative).


Create two new lists, one having all positive numbers and the other having all
negative numbers from the given list. Print all three lists.
Answer –
n = int(input(“Enter number of terms: “))
arr=[]
positive=[]
negative=[]
for i in range(n):
num=int(input())
arr.append(num)
for i in range(n):
if arr[i]>=0 :
positive.append(arr[i])
else:
negative.append(arr[i])
print(“Total positive numbers = “,positive)
print(“Total negative numbers = “,negative)
print(“All numbers = “,arr)

Output
Enter number of terms: 5
6
5
8
4
1
Total positive numbers = [6, 5, 8, 4, 1]
Total negative numbers = []
All numbers = [6, 5, 8, 4, 1]

3. Write a function that returns the largest element of the list passed as
parameter.
Answer –
def myfunction(arr):
max = arr[0]
for i in range(len(arr)):
if max<arr[i]:
max=arr[i]
return max
arr = [32,92,72,36,48,105]
print(myfunction(arr))

Output
105

4. Write a function to return the second largest number from a list of


numbers.
Answer –
def myfunction(new_list):
new_list.sort()
return new_list[len(new_list)-2]
new_list = [36,95,45,90,105]
print(myfunction(new_list))

Output
95

5. Write a program to read a list of n integers and find their median.


Note: The median value of a list of values is the middle one when they are
arranged in order. If there are two middle values then take their average.
Hint: You can use an built-in function to sort the list
Answer –
def myfunction(new_list):
new_list.sort()
indexes = len(new_list)
if(indexes%2 == 0):
num1 = (indexes) // 2
num2 = (indexes // 2) + 1
med = (new_list[num1 – 1] + new_list[num2 – 1]) / 2
return med
else:
middle = (indexes – 1) // 2
med = new_list[middle]
return med
new_list = list()
inp = int(input(“Enter Number of Terms : “))
for i in range(inp):
a = int(input(“Enter the Number: “))
new_list.append(a)
print(“The median value is”,myfunction(new_list))

Output
Enter Number of Terms : 5
Enter the Number: 6
Enter the Number: 5
Enter the Number: 8
Enter the Number: 4
Enter the Number: 6
The median value is 6
6. Write a program to read a list of elements. Modify this list so that it does
not contain any duplicate elements, i.e., all elements occurring multiple
times in the list should appear only once.
Answer –
def myfunction(list1):
length = len(list1)
new_list = []
for a in range(length):
if list1[a] not in new_list:
new_list.append(list1[a])
return new_list

list1 = []

inp = int(input(“Enter Terms : “))

for i in range(inp):
a = int(input(“Enter the number: “))
list1.append(a)

print(“The list is:”,list1)

print(“List without any duplicate element :”,myfunction(list1))

Output
Enter Terms : 5
Enter the number: 6
Enter the number: 4
Enter the number: 8
Enter the number: 1
Enter the number: 6
The list is: [6, 4, 8, 1, 6]
List without any duplicate element : [6, 4, 8, 1]

7. Write a program to read a list of elements. Input an element from the user
that has to be inserted in the list. Also input the position at which it is to be
inserted. Write a user defined function to insert the element at the desired
position in the list.
Answer –
arr=[114,25,68,84,79]
position = int(input(“Enter the position of the element: “))
element = int(input(“Enter element : “))
print(“The list before insertion : “,arr)
arr1 = arr[:position-1]+[element]+arr[position-1:]
print(“The list after insertion: “,arr1)
Output
Enter the position of the element: 2
Enter element : 75
The list before insertion : [114, 25, 68, 84, 79]
The list after insertion: [114, 75, 25, 68, 84, 79]

8. Read a list of n elements. Pass this list to a function which reverses this
list in-place without creating a new list.
Answer –
new_list=[98,78,54,89,76]
print(“Original list: “,new_list)
new_list.reverse()
print(“List after reversing “,new_list)

Output
Original list: [98, 78, 54, 89, 76]
List after reversing [76, 89, 54, 78, 98]

You might also like