Humanities/Arts Exam  >  Humanities/Arts Notes  >  Computer Science for Class 11  >  Chapter Notes: Lists

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts PDF Download

Introduction to Lists

In Python, a list is a fundamental data type that represents an ordered collection of elements. What sets lists apart is their mutability, meaning you can change, add, or remove elements after the list has been created. Unlike strings, which are made up of characters, lists can contain elements of different data types, including integers, floats, strings, tuples, or even other lists.

Lists are particularly useful for grouping together items of mixed data types. For example, you could have a list that contains an integer, a string, and a float all in one.

  • Creating a List: To create a list, you enclose the elements in square brackets [ ], separating them with commas.
  • Example: my_list = [1, 2, 3, 4, 5]
  • List Indices: Just like with strings, the indices for lists start at 0. This means the first element of the list is accessed with index 0, the second element with index 1, and so on.

Example:

Python provides a built-in data type called list to store a collection of data. A list is a mutable data type that is ordered and allows duplicate elements.

list1 is a list in Python that contains six even numbers. The numbers in the list are 2, 4, 6, 8, 10, and 12. When we print list1, we see the output as [2, 4, 6, 8, 10, 12].

list2 is a list in Python that contains the vowels 'a', 'e', 'i', 'o', and 'u'. When we print list2, we see the output as ['a', 'e', 'i', 'o', 'u'].

list3 is a list in Python that contains mixed data types, including an integer 100, a float 23.5, and a string 'Hello'. When we print list3, we see the output as [100, 23.5, 'Hello'].

list4 is a nested list in Python that contains three sublists, each representing a subject and its corresponding code. The sublists are ['Physics', 101], ['Chemistry', 202], and ['Maths', 303]. When we print list4, we see the output as [['Physics', 101], ['Chemistry', 202], ['Maths', 303]].

Accessing Elements in a List

The elements present in a list can be accessed in the same manner as characters are accessed in a string.

For example, if we have a list called  list1 , we can access its elements using their index positions, just like we would with a string.

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Lists are Mutable

In Python, lists are mutable, meaning their contents can be changed after the list has been created.

For example:

  • Original List: list1 = [ ' Red ' , ' Green ' , ' Blue ' , ' Orange ' ]
  • Modify the List: list1 [ 3 ] = ' Black '
  • Modified List: print ( list1 ) # Output: [ ' Red ' , ' Green ' , ' Blue ' , ' Black ' ]

List Operations

Lists in Python can be manipulated in various ways after they are created.

Concatenation

You can join two or more lists using the concatenation operator +.

Example:

  • List of Odd Integers: list1 = [ 1 , 3 , 5 , 7 , 9 ]
  • List of Even Integers: list2 = [ 2 , 4 , 6 , 8 , 10 ]
  • Concatenating Lists: list1 + list2
  • Output:. 1 , 3 , 5 , 7 , 9 , 2 , 4 , 6 , 8 , 10 ]

Example with Color Lists:

  • list3 = [ ' Red ' , ' Green ' , ' Blue ' ]
  • list4 = [ ' Cyan ' , ' Magenta ' , ' Yellow ' , ' Black ' ]
  • list3 + list4
  • Output: [ ' Red ' , ' Green ' , ' Blue ' , ' Cyan ' , ' Magenta ' , ' Yellow ' , ' Black ' ]

Important Notes:

  • Concatenation does not change the original lists.
  • If you want to merge two lists and create a new one, use an assignment statement.
  • The + operator can only be used with lists. Using it with other data types will raise a TypeError.
  • Example of TypeError: list1 + str1 where list1 is a list and str1 is a string.

Repetition

In Python, you can replicate a list using the repetition operator, which is represented by the symbol *.

For example:

  • list1 = ['Hello']
  • list1 * 4
  • Output: ['Hello', 'Hello', 'Hello', 'Hello']

Membership

Membership operators in Python, such as in and not in, are used to check whether an element is present in a list. These operators return True or False based on the presence of the element.

  • in operator: This operator checks if the specified element is present in the list.
  • not in operator: This operator checks if the specified element is not present in the list.

Slicing

Slicing is a technique that can be used on both strings and lists to extract specific portions of the data.

For example, consider the list:

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Traversing a List

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

(A) List Traversal Using for Loop
Example 1: Using a for loop to print each item in the list

Code:
Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Output:
Red 
Green 
Blue 
Yellow 
Black

Example 2: Accessing elements using range() and len() functions

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Code:
Red 
Green 
Blue 
Yellow 
Black

(B) List Traversal Using while Loop

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Code:
Red 
Green 
Blue 
Yellow 
Black

List Methods and Built-In Functions

Lists in Python come with a variety of built-in methods that are quite handy for programming tasks. 

Description

  • Returns the length of the list passed as the argument.
  • Creates an empty list if no argument is passed. If a sequence is passed as an argument, it creates a list from that sequence.
  • Appends a single element passed as an argument at the end of the list. The single element can also be a list.
  • Appends each element of the list passed as an argument to the end of the given list.
  • Inserts an element at a particular index in the list.
  • Returns the number of times a given element appears in the list.
  • Returns the index of the first occurrence of the element in the list. If the element is not present, a ValueError is generated.
  • 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, a ValueError is generated.
  • Returns and removes the element whose index is passed as a parameter to this function. If no parameter is given, it returns and removes the last element of the list.
  • Reverses the order of elements in the given list.
  • Sorts the elements of the given list in-place.
  • Takes a list as a parameter and creates a new list consisting of the same elements arranged in sorted order.
  • Returns the minimum or smallest element of the list.
  • Returns the maximum or largest element of the list.
  • Returns the sum of the elements of the list.

Nested Lists

A nested list is when a list is included as an element within another list.

Example

Let's say we have a list called  list1  that contains various elements, including another list as one of its elements:

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

In this example, the fifth element of  list1 is also a list:  [6, 7, 8] . When we access this element with list1[4] , we get the nested list.

To access elements within the nested list, we need to specify two indices:  list1[i][j]. Here,  i  indicates the index of the nested list within the main list, and  j  indicates the index of the element within the nested list.

For example, if we want to access the second element of the nested list in  list1, we can use:

list1[4][1]

This means:

  •  list1[4]  gives us the fifth element of  list1  , which is the nested list  [6, 7, 8].
  •  [1] then gives us the second element of this nested list, which is 7.

Copying Lists

When you have a list in Python and you want to make a copy of it, simply assigning it to another list will not work as expected. For example:

list1 = [1, 2, 3] list2 = list1

In this case, list2 does not create a new list. Instead, it makes list1 and list2 refer to the same list object in memory. This means that list2 becomes an alias for list1, and any changes made to either list will affect the other.

For instance:

  • list1.append(10)

list1 will now be [1, 2, 3, 10] list2 will also reflect this change.

To create a copy of the list as a distinct object, you can use one of the following methods:

  • Slicing: You can create a copy of the list using slicing.
  • Using the built-in list() function: This method creates a new list object.
  • Using the copy() function from the Python copy library: This method also creates a new list object.

Methods to Create a Copy of a List in Python

Method 1: Slicing

You can create a copy of a list by slicing it. This involves taking the entire list and storing it in a new variable. For example:

newList = oldList[:] 

Example
>>> list1 = [1, 2, 3, 4, 5]

Output
>>> list2 = list1[:] >>> list2 [1, 2, 3, 4, 5] 

Method 2: Using the list() Function
Another way to copy a list is by using the built-in  list()  function. This function takes an iterable and returns a new list. For instance:
newList = list(oldList) 

Example
>>> list2 = list(list1) 

Output
[10, 20, 30, 40]

Method 3: Using the copy() Function from the copy Library

You can also use the copy() function from the  copy library to create a copy of a list. First, you need to import the  copy  library and then use its  copy()  function. For example:

 import copy newList = copy.copy(oldList) 

Example:
>>> import copy 
>>> list1 = [1,2,3,4,5] 
>>> list2 = copy.copy(list1) 
>>> list2 [1, 2, 3, 4, 5]

List as argument to a Function

When a list is passed as an argument to a function in Python, there are two important scenarios to consider:

(A) Modifying the Original List

In this scenario, changes made to the list inside the function are reflected in the original list outside the function. This happens because when a list is passed as an argument, a reference to the list is passed, not a copy.

For example, consider the following program where a list of numbers, list1, is passed to a function called increment(). This function increases each element of the list by 5.

Program: Program to increment the elements of a list. The list is passed as an argument to a function.

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

Output:

  • Reference of list in Main: 70615968
  • Reference of list Inside Function: 70615968 (The ID remains the same)
  • The list after the function call: [15, 25, 35, 45, 55]

This example demonstrates that when a list is passed as an argument, any modifications made to it inside the function are reflected in the original list.

(B) Assigning a New Value to the List Inside the Function
If the list is assigned a new value inside the function, a new list object is created, and it becomes a local copy within the function. Changes made to this local copy do not affect the original list in the calling function.

For instance, consider the following program:

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

# 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] # Assigning a new list to list2
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] # 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)

Output:

  • ID of list before function call: 65565640
  • ID of list inside function before assignment: 65565640
  • ID of list changes inside function after assignment: 65565600
  • ID of list after function call: 65565640

List Manipulation

In this chapter, we have learned how to create a list and the different ways to manipulate lists. In the following programs, we will apply various list manipulation methods.

Program: 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.

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts
Output:
How many numbers do you want to enter in the list: 5
Enter a list of numbers: 23
567
12
89
324
Enter the number to be searched:12 
Number 12 is present at 3 position

The document Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Computer Science for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
33 docs|11 tests

FAQs on Lists Chapter Notes - Computer Science for Class 11 - Humanities/Arts

1. What are the basic operations that can be performed on a list in Python?
Ans. Basic operations on a list in Python include creating a list, accessing elements using indexing, adding elements using methods like `append()` and `extend()`, removing elements with `remove()` and `pop()`, and modifying elements by assigning new values to specific indices. Additionally, you can check the length of a list using `len()`, and you can concatenate lists using the `+` operator.
2. How can I traverse a list in Python?
Ans. You can traverse a list in Python using a `for` loop, which iterates over each element in the list. For example, you can write `for item in my_list:` to perform operations on each `item`. Alternatively, you can use a `while` loop with an index to access elements by their positions.
3. What are some common list methods and built-in functions in Python?
Ans. Some common list methods include `append()`, `insert()`, `remove()`, `pop()`, `sort()`, and `reverse()`. Built-in functions that can be used with lists include `len()`, `max()`, `min()`, `sum()`, and `sorted()`. These methods and functions help manage and manipulate list data effectively.
4. What is a nested list, and how do I access its elements?
Ans. A nested list is a list that contains other lists as its elements. You can access elements in a nested list using multiple indices. For example, if you have a nested list `nested_list = [[1, 2, 3], [4, 5, 6]]`, you can access the number `5` by using `nested_list[1][1]`, where `1` refers to the second list and the second `1` refers to the second element of that list.
5. How can I copy a list in Python, and what are the differences between shallow and deep copies?
Ans. You can copy a list in Python using the `copy()` method or by using slicing (`new_list = old_list[:]`). A shallow copy creates a new list but does not create copies of the nested objects, meaning changes in the nested objects will reflect in both lists. A deep copy, created using the `copy` module's `deepcopy()` function, creates a new list and recursively copies all nested objects, so changes in the copied list do not affect the original list.
Related Searches

past year papers

,

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

Important questions

,

Objective type Questions

,

study material

,

mock tests for examination

,

Extra Questions

,

video lectures

,

Free

,

Sample Paper

,

MCQs

,

practice quizzes

,

Exam

,

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

Viva Questions

,

Lists Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

ppt

,

Summary

,

shortcuts and tricks

,

pdf

,

Semester Notes

,

Previous Year Questions with Solutions

;