Lists - Class 11 Computer Science - Chapter 9 - Notes, NCERT Solutions & Extra Questions
Renews every month. Cancel anytime
Your personal doubt-solving assistant
Chatterbot AI gives you 100% accurate answers to your questions in an instant.
Notes - Lists | Class 11 NCERT | Computer Science
Comprehensive Class 11 Notes on Python Lists
Introduction to Lists
In Python, a list is an ordered sequence that is mutable, meaning its elements can be changed after creation. Lists are incredibly versatile as they can contain elements of various data types, including integers, floats, strings, and even other lists. This makes them invaluable in programming for grouping different types of elements together.
Creating a List in Python
To create a list, you enclose the elements in square brackets ([]
), separated by commas. Let's look at some examples:
### List of integers
list1 = [2, 4, 6, 8, 10, 12]
### List of vowels
list2 = ['a', 'e', 'i', 'o', 'u']
### List with mixed data types
list3 = [100, 23.5, 'Hello']
### Nested list (list within a list)
list4 = [['Physics', 101], ['Chemistry', 202], ['Maths', 303]]
Here's how different lists might look visually:
Working with Lists
Accessing Elements in a List
Accessing elements in a list is straightforward and similar to accessing characters in a string. The indices start from 0. For example:
list1 = [2, 4, 6, 8, 10, 12]
print(list1[0]) # Outputs: 2
print(list1[3]) # Outputs: 8
print(list1[-1]) # Outputs: 12 (last element)
Determining the Length of a List
You can determine the length of a list using the len()
function:
list1 = [2, 4, 6, 8, 10, 12]
print(len(list1)) # Outputs: 6
List Mutations
Modifying Elements in a List
Lists are mutable, meaning you can change their elements:
list1 = ['Red', 'Green', 'Blue', 'Orange']
list1[3] = 'Black'
print(list1) # Outputs: ['Red', 'Green', 'Blue', 'Black']
List Operations
Concatenation
You can concatenate (join) two or more lists using the +
operator:
list1 = [1, 3, 5, 7, 9]
list2 = [2, 4, 6, 8, 10]
combined_list = list1 + list2
print(combined_list) # Outputs: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
Repetition
Use the *
operator to repeat lists:
list1 = ['Hello']
print(list1 * 4) # Outputs: ['Hello', 'Hello', 'Hello', 'Hello']
Membership
Check if an element is in a list using in
and not in
:
list1 = ['Red', 'Green', 'Blue']
print('Green' in list1) # Outputs: True
print('Cyan' not in list1) # Outputs: True
Slicing
Extract parts of a list using slicing. The syntax is list[start:end:step]
:
list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
print(list1[2:6]) # Outputs: ['Blue', 'Cyan', 'Magenta', 'Yellow']
print(list1[::2]) # Outputs: ['Red', 'Blue', 'Magenta', 'Black']
print(list1[::-1]) # Outputs: ['Black', 'Yellow', 'Magenta', 'Cyan', 'Blue', 'Green', 'Red']
Traversing a List
You can traverse a list using loops.
Using a For Loop
list1 = ['Red', 'Green', 'Blue', 'Yellow', 'Black']
for item in list1:
print(item)
Using a While Loop
list1 = ['Red', 'Green', 'Blue', 'Yellow', 'Black']
i = 0
while i < len(list1):
print(list1[i])
i += 1
List Methods and Built-in Functions
Common Methods
Method | Description | Example |
---|---|---|
len() |
Returns the length of the list | len([10, 20, 30, 40, 50]) → 5 |
append() |
Appends an element to the end of the list | list1.append(50) |
extend() |
Appends each element of the argument list to the list | list1.extend([40, 50]) |
insert() |
Inserts an element at the specified index | list1.insert(2, 25) |
count() |
Returns the count of the specified element in the list | list1.count(10) |
index() |
Returns index of the first occurrence of the element | list1.index(20) |
remove() |
Removes the first occurrence of the element | list1.remove(30) |
pop() |
Removes and returns the element at the specified index | list1.pop(3) |
sort() |
Sorts the list in ascending order | list1.sort() |
reverse() |
Reverses the order of the list | list1.reverse() |
Nested Lists
A nested list is a list within another list:
list1 = [1, 2, 'a', 'c', [6, 7, 8], 4, 9]
print(list1[4]) # Outputs: [6, 7, 8]
print(list1[4][1]) # Outputs: 7
Here's a visual representation of accessing nested lists:
graph TD;
A1[List1[1]] --> A1_1[1]
A2[List1[2]] --> A2_1[2]
A3[List1[4]] --> A3_1[6]
A3 --> A3_2[7]
A3 --> A3_3[8]
Copying Lists
Assignment vs. Copying
Assigning a list to another variable does not create a new list; both variables point to the same list object:
list1 = [1, 2, 3]
list2 = list1
list1.append(10)
print(list2) # Outputs: [1, 2, 3, 10]
To create a copy:
### Method 1: Using slicing
list2 = list1[:]
### Method 2: Using list() function
list2 = list(list1)
### Method 3: Using copy library
import copy
list2 = copy.copy(list1)
Lists as Arguments to Functions
Passing lists to functions can be done easily:
def increment(list2):
for i in range(len(list2)):
list2[i] += 5
list1 = [10, 20, 30, 40, 50]
increment(list1)
print(list1) # Outputs: [15, 25, 35, 45, 55]
List Manipulation Exercises
Here are some common list manipulation tasks:
Average Marks Calculation
def compute_average(marks):
return sum(marks)/len(marks)
marks = [45, 89, 79, 76, 55]
average = compute_average(marks)
print(f"Average: {average}")
Find Largest Element
def find_largest(lst):
return max(lst)
numbers = [2, 5, 1, 9, 4]
print(f"Largest: {find_largest(numbers)}")
Remove Duplicates
def remove_duplicates(lst):
return list(set(lst))
elements = [1, 2, 2, 3, 4, 4, 5]
print(remove_duplicates(elements)) # Outputs: [1, 2, 3, 4, 5]
Summary
- Lists are mutable sequences in Python and can contain elements of different data types.
- They allow various operations like concatenation, repetition, and slicing.
- Traversing a list can be done using loops.
- Python provides multiple list manipulation methods that are essential for different programming tasks.
By mastering the list operations and methods detailed above, you will be well-equipped to handle various programming challenges that involve data manipulation. Happy coding!
🚀 Learn more about Notes with Chatterbot AI
Extra Questions - Lists | NCERT | Computer Science | Class 11
💡 Have more questions?
Ask Chatterbot AINCERT Solutions - Lists | NCERT | Computer Science | Class 11
What will be the output of the following statements?
i.
list1 = [12,32,65,26,80,10]
list1.sort()
print(list1)
ii.
list1 = [12,32,65,26,80,10]
sorted(list1)
print(list1)
iii.
list1 = [1,2,3,4,5,6,7,8,9,10]
list1[::-2]
list1[:3] + list1[3:]
iv.
list1 = [1,2,3,4,5]
list1[len(list1)-1]
Output for the given statements:
i.
list1 = [12, 32, 65, 26, 80, 10]
list1.sort()
print(list1)
Output:
[10, 12, 26, 32, 65, 80]
Explanation: The sort()
method modifies list1
in place to be in ascending order.
ii.
list1 = [12, 32, 65, 26, 80, 10]
sorted(list1)
print(list1)
Output:
[12, 32, 65, 26, 80, 10]
Explanation: The sorted()
function returns a new sorted list, leaving list1
unchanged.
iii.
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list1[::-2]
list1[:3] + list1[3:]
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation: The slicing operations list1[::-2]
and list1[:3] + list1[3:]
do not modify list1
. They produce new lists which are not assigned to any variable. So, the original list1
remains unchanged.
iv.
list1 = [1, 2, 3, 4, 5]
list1[len(list1)-1]
Output:
5
Explanation: list1[len(list1)-1]
returns the last element of list1
, which is 5.
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])
ii. myList.extend([80, 90])
After performing the provided operations on myList
, the changes will be as follows:
myList.append([50,60])
The
append
method will add[50, 60]
as a single element (nested list) at the end ofmyList
.Result:
myList = [10, 20, 30, 40, [50, 60]]
myList.extend([80, 90])
The
extend
method will add each element of[80, 90]
individually to the end ofmyList
.Result:
myList = [10, 20, 30, 40, [50, 60], 80, 90]
So, the final elements of myList
after both operations will be:
[10, 20, 30, 40, [50, 60], 80, 90]
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])
The code iterates through the list myList
and prints the elements at even indices. The output will be the elements at indices 0, 2, 4, 6, and 8:
1
3
5
7
9
To summarize, the output of this code segment is:
1
3
5
7
9
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)
b.
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)
c.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList [:2]
print(myList)
Output
a.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[3:]
print(myList)
The output will be:
[1, 2, 3]
Explanation: The del myList[3:]
statement removes elements from the list starting at index 3 until the end of the list.
b.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[:5]
print(myList)
The output will be:
[6, 7, 8, 9, 10]
Explanation: The del myList[:5]
statement removes elements from the start of the list up to (but not including) index 5.
c.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[:2]
print(myList)
The output will be:
[3, 4, 5, 6, 7, 8, 9, 10]
Explanation: The del myList[:2]
statement removes elements from the start of the list up to (but not including) index 2.
Differentiate between append() and extend() functions of list.
The append()
and extend()
functions in Python lists serve different purposes:
append():
Purpose: Adds a single element to the end of the list.
Effect: The added element can be of any data type, including another list.
Example:
list1 = [1, 2, 3] list1.append(4) # Output: [1, 2, 3, 4] list1.append([5, 6]) # Output: [1, 2, 3, 4, [5, 6]]
extend():
Purpose: Adds each element of an iterable (e.g., list, tuple) to the end of the list.
Effect: The elements of the iterable are added individually.
Example:
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) # Output: [1, 2, 3, 4, 5, 6]
In summary, append()
adds its argument as a single element to the list, while extend()
iterates over its argument adding each element individually to the list.
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
Here's the difference between the operations:
a. list1 * 2
This operation replicates the list
list1
two times.It returns a new list without modifying
list1
.
list1 = [6, 7, 8, 9]
result = list1 * 2
print(result) # Output: [6, 7, 8, 9, 6, 7, 8, 9]
print(list1) # Output: [6, 7, 8, 9]
b. list1 *= 2
This operation modifies the original list
list1
by replicating its elements two times in place.The original list
list1
is updated.
list1 = [6, 7, 8, 9]
list1 *= 2
print(list1) # Output: [6, 7, 8, 9, 6, 7, 8, 9]
c. list1 = list1 * 2
Similar to (a), this creates a new list by replicating
list1
two times.The original list
list1
is replaced with this new list.
list1 = [6, 7, 8, 9]
list1 = list1 * 2
print(list1) # Output: [6, 7, 8, 9, 6, 7, 8, 9]
Summary
list1 * 2
: Creates a new list, leaveslist1
unchanged.list1 *= 2
: Modifieslist1
in place.list1 = list1 * 2
: Creates a new list and reassigns it tolist1
.
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
b) Marks in the fifth subject
c) Maximum marks of the student
d) Roll no. of the student
e) Change the name of the student from 'Raman' to 'Raghav'
# Given student record
stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8]
# a) Percentage of the student
percentage = stRecord[3]
print("Percentage of the student:", percentage)
# b) Marks in the fifth subject
marks_fifth_subject = stRecord[2][4]
print("Marks in the fifth subject:", marks_fifth_subject)
# c) Maximum marks of the student
max_marks = max(stRecord[2])
print("Maximum marks of the student:", max_marks)
# d) Roll no. of the student
roll_no = stRecord[1]
print("Roll no. of the student:", roll_no)
# e) Change the name of the student from 'Raman' to 'Raghav'
stRecord[0] = 'Raghav'
print("Updated student record:", stRecord)
Output:
Percentage of the student: 78.8
Marks in the fifth subject: 69
Maximum marks of the student: 99
Roll no. of the student: A-36
Updated student record: ['Raghav', 'A-36', [56, 98, 99, 72, 69], 78.8]
Explanation:
a) To retrieve the percentage, access the fourth element of the list
stRecord[3]
.b) To retrieve the marks in the fifth subject, access the fifth element of the nested list
stRecord[2][4]
.c) To retrieve the maximum marks, use the
max()
function on the nested liststRecord[2]
.d) To retrieve the roll number, access the second element of the list
stRecord[1]
.e) To change the name from 'Raman' to 'Raghav', update the first element of the list
stRecord[0]
.
Write a program to find the number of times an element occurs in the list.
Here's a Python program that counts the number of occurrences of a specific element in a list:
def count_occurrences(my_list, element):
"""Function to count occurrences of an element in a list."""
count = my_list.count(element)
return count
# Example list and element to count
my_list = [1, 2, 3, 4, 1, 2, 1, 1, 5, 1]
element = 1
# Call the function and print the result
occurrences = count_occurrences(my_list, element)
print(f"The element {element} occurs {occurrences} times in the list.")
Output:
The element 1 occurs 5 times in the list.
In this program:
We define a function
count_occurrences
that uses thecount()
method of the list to find the number of times an element appears.We input a sample list
my_list
and the element to be counted.We call the function and print out the number of occurrences.
Write a program to read a list of $\mathrm{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.
Here is a Python program that reads a list of n
integers, and creates two new lists: one with all the positive numbers and the other with all the negative numbers. Then, it prints all three lists.
# Function to separate positive and negative numbers
def separate_numbers(input_list):
positive_list = []
negative_list = []
for number in input_list:
if number >= 0:
positive_list.append(number)
else:
negative_list.append(number)
return positive_list, negative_list
# Main program
input_list = []
# Reading the number of integers
n = int(input("Enter the number of integers: "))
# Reading the integers
for i in range(n):
num = int(input(f"Enter integer {i + 1}: "))
input_list.append(num)
# Separate the numbers into positive and negative lists
positive_list, negative_list = separate_numbers(input_list)
# Print the three lists
print("Original list:", input_list)
print("Positive numbers list:", positive_list)
print("Negative numbers list:", negative_list)
Important points:
Reading Input: The program first asks the user for the number of integers and then reads each integer.
Separating Numbers: The function
separate_numbers
takes the original list and separates it into two lists based on whether the numbers are positive or negative.Output: Finally, the program prints the original list, the list of positive numbers, and the list of negative numbers.
Write a function that returns the largest element of the list passed as parameter.
Here is a function in Python that returns the largest element of a list passed as a parameter:
def find_largest_element(lst):
if not lst:
return None # Handle the case for empty list
largest = lst[0]
for element in lst[1:]:
if element > largest:
largest = element
return largest
# Example usage:
my_list = [10, 20, 30, 40, 50]
largest_element = find_largest_element(my_list)
print("The largest element is:", largest_element)
Explanation:
The function
find_largest_element(lst)
takes a listlst
as a parameter.First, it checks if the list is empty; if so, it returns
None
.It initializes the variable
largest
with the first element of the list.It then iterates through the rest of the list, updating the
largest
variable whenever a larger element is found.Finally, it returns the largest element found.
Output:
The largest element is: 50
Write a function to return the second largest number from a list of numbers.
Here's a function to return the second largest number from a list of numbers:
def second_largest(numbers):
# Sort the list in descending order
sorted_numbers = sorted(numbers, reverse=True)
# Return the second element in the sorted list
return sorted_numbers[1]
# Example usage:
numbers = [10, 20, 4, 45, 99]
result = second_largest(numbers)
print("The second largest number is:", result)
Explanation:
Sorting: The list is sorted in descending order.
Second Element: The second element in this sorted list will be the second largest number.
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
Here is a Python program that reads a list of ( n ) integers from the user and computes the median of the list:
def find_median(nums):
# Sort the list
nums.sort()
# Find the length of the list
n = len(nums)
# If the number of elements is odd, return the middle element
if n % 2 != 0:
median = nums[n // 2]
else:
# If the number of elements is even, return the average of the two middle elements
mid1 = nums[n // 2]
mid2 = nums[(n // 2) - 1]
median = (mid1 + mid2) / 2
return median
# Read the list of numbers from the user
n = int(input("Enter the number of elements: "))
nums = []
for i in range(n):
elem = int(input(f"Enter element {i+1}: "))
nums.append(elem)
# Find and print the median
median = find_median(nums)
print(f"The median of the list is: {median}")
Explanation:
The
find_median
function takes a list of integers as input and sorts it.The median is found by checking if the length of the list (
n
) is odd or even:If odd, the middle element is returned.
If even, the average of the two middle elements is returned.
The user is prompted to enter the number of elements and then the individual elements of the list.
Finally, the program computes and prints the median of the list.
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.
To write a program that removes duplicate elements from a list, you can use Python's features such as sets or list comprehensions. Below is a sample program that accomplishes this task:
def remove_duplicates(original_list):
unique_list = []
for element in original_list:
if element not in unique_list:
unique_list.append(element)
return unique_list
# Read list of elements from the user
print("Enter the elements of the list separated by spaces:")
input_list = list(map(int, input().split()))
# Remove duplicates
modified_list = remove_duplicates(input_list)
# Print the modified list
print("\nThe list after removing duplicates is:")
print(modified_list)
Explanation:
Function to Remove Duplicates:
remove_duplicates(original_list)
: This function takes a list as input and creates an empty list calledunique_list
. It iterates through the elements of theoriginal_list
, checking if each element is already inunique_list
. If it is not, the element is added tounique_list
.
Read Input:
The program prompts the user to enter the elements of the list separated by spaces. These elements are read and converted to a list of integers.
Remove Duplicates:
The
remove_duplicates
function is called with the user's list, and the result is stored inmodified_list
.
Output the Result:
The modified list without duplicates is printed.
Sample Run:
Enter the elements of the list separated by spaces:
1 2 2 3 4 4 5
The list after removing duplicates is:
[1, 2, 3, 4, 5]
This program ensures that the list does not contain any duplicate elements by checking each element before adding it to the new list.
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.
Here is a Python program that reads a list of elements, asks the user for an element to be inserted and the position at which it should be inserted, and uses a user-defined function to perform the insertion:
def insert_element(my_list, element, position):
"""
Inserts an element at the specified position in the list.
Parameters:
my_list (list): The list where the element will be inserted.
element: The element to be inserted.
position (int): The position at which to insert the element.
"""
if 0 <= position <= len(my_list):
my_list.insert(position, element)
else:
print("Invalid position")
# Main program
my_list = []
# Reading list elements
n = int(input("Enter the number of elements in the list: "))
for i in range(n):
element = input(f"Enter element {i+1}: ")
my_list.append(element)
# Input element to be inserted and the position
new_element = input("Enter the element to be inserted: ")
position = int(input("Enter the position at which to insert the element: "))
# Inserting the element using the user-defined function
insert_element(my_list, new_element, position)
# Display the updated list
print("Updated list:", my_list)
Explanation:
Function Definition:
insert_element(my_list, element, position)
is defined to insert an element at a specified position in a given list.List Input: The main program reads
n
elements from the user to create the original list.Element and Position Input: The program prompts the user to enter the element to be inserted and the position for insertion.
Element Insertion: The
insert_element
function is called to insert the element at the specified position.Output: The updated list is printed.
Make sure to test the program for various edge cases, such as inserting an element at the start or end of the list or handling invalid positions.
Write a program to read elements of a list.
a) The program should ask for the position of the element to be deleted from the list. Write a function to delete the element at the desired position in the list.
b) The program should ask for the value of the element to be deleted from the list. Write a function to delete the element of this value from the list.
Here is a Python program to read elements into a list and then provide functionality for deleting an element by its position or by its value.
# Function to delete an element at a desired position
def delete_by_position(lst, pos):
if 0 <= pos < len(lst):
lst.pop(pos)
else:
print("Position out of range")
# Function to delete the first occurrence of an element by its value
def delete_by_value(lst, value):
if value in lst:
lst.remove(value)
else:
print("Value not found in the list")
# Main program
if __name__ == "__main__":
# Read elements into the list
myList = []
n = int(input("How many elements do you want to enter in the list: "))
for i in range(n):
elem = input(f"Enter element {i+1}: ")
myList.append(elem)
print("\nCurrent List:", myList)
# Delete by position
pos = int(input("\nEnter the position of the element to be deleted: "))
delete_by_position(myList, pos)
print("List after deleting element by position:", myList)
# Delete by value
value = input("\nEnter the value of the element to be deleted: ")
delete_by_value(myList, value)
print("List after deleting element by value:", myList)
This program includes two functions:
delete_by_position(lst, pos)
: This function removes the element at the given position.delete_by_value(lst, value)
: This function removes the first occurrence of the element with the given value.
The program then reads a list of elements, allows the user to delete an element by position, and delete an element by value.
Read a list of $\mathrm{n}$ elements. Pass this list to a function which reverses this list in-place without creating a new list.
Here is a program that reads a list of ( n ) elements and passes it to a function that reverses the list in place without creating a new list:
# Function to reverse the list in place
def reverse_list_in_place(lst):
left = 0
right = len(lst) - 1
while left < right:
# Swap the elements at positions left and right
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
# Read the number of elements
n = int(input("Enter the number of elements in the list: "))
# Read the list elements
lst = []
for i in range(n):
element = int(input(f"Enter element {i+1}: "))
lst.append(element)
print("Original list:", lst)
# Reverse the list in place
reverse_list_in_place(lst)
print("Reversed list:", lst)
Explanation
Function
reverse_list_in_place(lst)
:It takes a list
lst
.Two pointers
left
andright
are initialized to the start and end of the list.Elements are swapped while
left
is less thanright
, and pointers are moved closer to each other.
Reading input:
The user is prompted to enter the number of elements (
n
).A loop is used to read
n
elements from the user and append them to the listlst
.
Displaying results:
The original list is displayed.
The list is passed to
reverse_list_in_place(lst)
to reverse it.The reversed list is displayed.
This ensures that the list is reversed in-place without creating a new list.
💡 Have more questions?
Ask Chatterbot AI