0% found this document useful (0 votes)
41 views8 pages

Chapter 9 Lists

Read well

Uploaded by

woparac361
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)
41 views8 pages

Chapter 9 Lists

Read well

Uploaded by

woparac361
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/ 8

Chapter 9 Lists

Chapter 9: Lists

1. Introduction to List
• Definition: A list is an ordered sequence of elements that is mutable. Elements can be of
different data types, including integers, floats, strings, tuples, and other lists.
• Syntax: Elements are enclosed in square brackets and separated by commas. Indices start
from 0.
Example 9.1:
[2]:
list1 = [2, 4, 6, 8, 10, 12]
list2 = ['a', 'e', 'i', 'o', 'u']
list3 = [100, 23.5, 'Hello']
list4 = [['Physics', 101], ['Chemistry', 202], ['Maths', 303]]
• list1: List of even numbers.
• list2: List of vowels.
• list3: List with mixed data types.
• list4: Nested list.

2. Accessing Elements in a List


• Accessing by Index: Use square brackets and the index.

[ ]: list1[0] # returns 2
list1[3] # returns 8
list1[-1] # returns 12 (last element)

3. Lists are Mutable


• Mutability: Elements can be changed.

[ ]: list1 = ['Red', 'Green', 'Blue', 'Orange']


list1[3] = 'Black' # list1 becomes ['Red', 'Green', 'Blue', 'Black']

1
Chapter 9 Lists

4. List Operations 4.1 Concatenation - Joining Lists: Using +.

[3]: list1 + list2 # concatenates list1 and list2

[3]: [2, 4, 6, 8, 10, 12, 'a', 'e', 'i', 'o', 'u']

4.2 Repetition - Replicating Lists: Using *.

[ ]: list1 * 4 # repeats list1 four times

4.3 Membership - Checking Membership: Using in and not in.

[5]: 'Green' in list1 # returns True


'Cyan' not in list1 # returns True

[5]: True

4.4 Slicing - Extracting Sub-lists: Using slicing syntax.

[ ]: list1[2:6] # slices list1 from index 2 to 5


list1[::-1] # reverses the list

5. Traversing a List
• Using for Loop:

[ ]: for item in list1:


print(item)

• Using while Loop:

[ ]: i = 0
while i < len(list1):
print(list1[i])
i += 1

6. List Methods and Built-in Functions 6.1 Methods

Method Description Example


append Adds a single element at the end list1.append(50)
extend Adds elements of another list list1.extend(list2)
insert Inserts an element at a specific index list1.insert(2, 25)
count Returns the count of a specific element list1.count(10)
index Returns the index of the first occurrence of an list1.index(20)
element
remove Removes the first occurrence of an element list1.remove(30)
pop Removes and returns an element at a specific list1.pop(3)
index
reverse Reverses the order of elements list1.reverse()
sort Sorts the list list1.sort()

2
Chapter 9 Lists

6.2 Built-in Functions

Function Description Example


len Returns the number of elements len(list1)
list Creates a list list('aeiou')
min Returns the smallest element min(list1)
max Returns the largest element max(list1)
sum Returns the sum of elements sum(list1)
sorted Returns a new sorted list sorted(list1)

Experimnt all the built-in functions and methods using the examples in the table:

[ ]:

7. Nested Lists
• Definition: Lists within lists.

[ ]: list1 = [1, 2, 'a', 'c', [6, 7, 8], 4, 9]


list1[4] # returns [6, 7, 8]

8. Copying Lists Methods to Copy Lists: 1. Slicing:

[6]: list2 = list1[:]

2. Using list():

[ ]: list2 = list(list1)
3. Using copy module:

[ ]: list2 = copy.copy(list1)
3. Using copy module:

[ ]: import copy
list2 = copy.copy(list1)

9. List as Argument to a Function


• Passing Lists to Functions:

[ ]: def increment(list2):
for i in range(len(list2)):
list2[i] += 5
print(list2)

increment(list1)

3
Chapter 9 Lists

List Manipulation Program 9-1

[ ]: # Function to increment the elements of the list passed as argument


def increment(list2):
for i in range(0,len(list2)):
# 5 is added to individual elements in the list
list2[i] += 5
print('Reference of list Inside Function',id(list2))

# end of function
list1 = [10,20,30,40,50] # Create a list
print("Reference of list in Main",id(list1))
print("The list before the function call")
print(list1)
increment(list1) # list1 is passed as parameter to function
print("The list after the function call")
print(list1)

Explanation: This program demonstrates how passing a list to a function affects its elements. The
increment function adds 5 to each element in the list. The list reference inside the function is the
same as the reference in the main program, showing that the function modifies the original list.
Program 9-2

[ ]: # 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] # List2 assigned a new list
print("ID of list changes inside function after assignment:", id(list2))
print("The list inside the function after assignment is:")
print(list2)

# end of function
list1 = [10,20,30,40,50] # Create a list
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)

Program 9-3: Menu-Driven Program for List Operations Explanation: This program
provides a menu-driven interface to perform various list operations such as appending elements,
inserting elements at a desired position, appending another list, modifying elements, deleting ele-
ments, sorting the list, and displaying the list.

4
Chapter 9 Lists

[ ]: # Menu driven program to do various list operations


myList = [22, 4, 16, 38, 13] # myList already has 5 elements
choice = 0
while True:
print("The list 'myList' has the following elements", myList)
print("\nL I S T O P E R A T I O N S")
print(" 1. Append an element")
print(" 2. Insert an element at the desired position")
print(" 3. Append a list to the given list")
print(" 4. Modify an existing element")
print(" 5. Delete an existing element by its position")
print(" 6. Delete an existing element by its value")
print(" 7. Sort the list in ascending order")
print(" 8. Sort the list in descending order")
print(" 9. Display the list")
print(" 10. Exit")
choice = int(input("ENTER YOUR CHOICE (1-10): "))

# append element
if choice == 1:
element = int(input("Enter the element to be appended: "))
myList.append(element)
print("The element has been appended\n")

# insert an element at desired position


elif choice == 2:
element = int(input("Enter the element to be inserted: "))
pos = int(input("Enter the position:"))
myList.insert(pos, element)
print("The element has been inserted\n")

# append a list to the given list


elif choice == 3:
newList = eval(input("Enter the elements separated by commas"))
myList.extend(list(newList))
print("The list has been appended\n")

# modify an existing element


elif choice == 4:
pos = int(input("Enter the position of the element to be modified: "))
element = int(input("Enter the new element: "))
myList[pos] = element
print("The element has been modified\n")

# delete an existing element by its position


elif choice == 5:
pos = int(input("Enter the position of the element to be deleted: "))

5
Chapter 9 Lists

myList.pop(pos)
print("The element has been deleted\n")

# delete an existing element by value


elif choice == 6:
element = int(input("\nEnter the element to be deleted: "))
if element in myList:
myList.remove(element)
print("\nThe element", element, "has been deleted\n")
else:
print("\nElement", element, "is not present in the list")

# sort the list in ascending order


elif choice == 7:
myList.sort()
print("\nThe list has been sorted")

# sort the list in descending order


elif choice == 8:
myList.sort(reverse=True)
print("\nThe list has been sorted in reverse order")

# display the list


elif choice == 9:
print("\nThe list is:", myList)

# exit from the menu


elif choice == 10:
break
else:
print("Choice is not valid")
print("\n\nPress any key to continue. ........................ ")
ch = input()

Program 9-4: Explanation: A program to calculate average of marks of n students, n is an input


value to refer number of students..r.

[ ]: #Program 9-4
#Function to calculate average marks of n students
def computeAverage(list1,n):
#initialize total
total = 0
for marks in list1:
#add marks to total
total = total + marks
average = total / n
return average

6
Chapter 9 Lists

#create an empty list


list1 = []

print("How many students marks you want to enter: ")


n = int(input())

for i in range(0,n):
print("Enter marks of student",(i+1),":")
marks = int(input())
#append marks in the list
list1.append(marks)

average = computeAverage(list1,n)
print("Average marks of",n,"students is:",average)
Program 9-5:
Write a user-defined function to check if a number is present in the list or not. If the number is
present, return the position of the number. Print an appropriate message if the number is not
present in the list.

[ ]: #Program 9-5
#Function to check if a number is present in the list or not
def linearSearch(num,list1):
for i in range(0,len(list1)):
if list1[i] == num: #num is present
return i #return the position
return None #num is not present in the list
#end of function

list1 = [] #Create an empty list


print("How many numbers do you want to enter in the list: ")
maximum = int(input())
print("Enter a list of numbers: ")
for i in range(0,maximum):
n = int(input())
list1.append(n) #append numbers to the list

num = int(input("Enter the number to be searched: "))


result = linearSearch(num,list1)
if result is None:
print("Number",num,"is not present in the list")
else:
print("Number",num,"is present at",result + 1, "position")

Exercises
1. Write a program to create a list of first 10 natural numbers.

7
Chapter 9 Lists

[ ]:

2. Write a program to find the sum of all elements in a list.

[ ]:

3. Write a program to reverse the elements of a list.

[ ]:

You might also like