Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 7: Lists in Python

A list is an ordered sequence of elements, which can be of any data type. Unlike strings, lists are mutable, meaning we can modify their contents after creation. Lists are enclosed in square brackets [] and elements are separated by commas.

7.1 Indexing and Operations

Lists support indexing just like strings.

  • Forward indexing starts from 0.
  • Backward indexing starts from -1.

List Operations

  • Concatenation (+): Joins two lists. [1, 2] + [3, 4] results in [1, 2, 3, 4].
  • Repetition (*): Repeats the list. [1] * 3 results in [1, 1, 1].
  • Membership (in, not in): Checks if an item exists in the list.
  • Slicing ([start:stop:step]): Extracts a sub-list.
    L = [10, 20, 30, 40, 50]
    print(L[1:4]) # Output: [20, 30, 40]
    

7.2 Traversing a List

You can traverse a list using loops to access elements.

L = [10, 20, 30]
# Using a for loop directly
for num in L:
    print(num)

# Using indexing with range and len
for i in range(len(L)):
    print(L[i])

7.3 Built-in Functions and Methods

Python provides many functions and methods to work with lists.

  • len(list): Returns number of elements.
  • list(sequence): Converts a sequence to a list.
  • append(item): Adds a single item to the end of the list.
  • extend(iterable): Appends elements from another iterable (like a list) to the end.
  • insert(index, item): Inserts an item at a specific index.
  • count(item): Returns the number of times item appears.
  • index(item): Returns the first index of item.
  • remove(item): Removes the first occurrence of item. Raises ValueError if not found.
  • pop([index]): Removes and returns the item at index (default is the last item).
  • reverse(): Reverses the elements of the list in-place.
  • sort(): Sorts the list in ascending order in-place.
  • sorted(list): Returns a new sorted list without modifying the original.
  • min(list) / max(list) / sum(list): Returns the minimum, maximum, and sum of numeric lists.

7.4 Nested Lists

A list can contain another list as its element. This is called a nested list (used to represent matrices or 2D arrays).

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0][1]) # Output: 2

7.5 Common List Programs

Finding an element in a list by checking sequentially.

L = [4, 2, 9, 7, 5]
search_key = 7
found = False

for i in range(len(L)):
    if L[i] == search_key:
        print("Element found at index:", i)
        found = True
        break

if not found:
    print("Element not found")

2. Frequency of Elements

Counting how many times a specific element appears in a list.

L = [1, 2, 2, 3, 2, 4]
target = 2
count = 0
for num in L:
    if num == target:
        count += 1
print("Frequency of", target, "is:", count)

Competency Based Questions

Q1. Predict the Output What will be the output of the following code?

L = [10, 20, 30]
L.append([40, 50])
L.extend([60, 70])
print(len(L))
print(L[3])

Q2. Find the Error Ankit wrote the following code to double every element in a list. But when he prints the list, the elements are unchanged. Why?

L = [1, 2, 3]
for i in L:
    i = i * 2
print(L)

Provide the corrected code.

Q3. Case-Based Scenario A teacher wants to maintain a list of marks for her students. She wants to add a new student’s marks (85) exactly at the 3rd position in the list. Which list method should she use? Write the line of code assuming her list is named marks_list.

Q4. Application-Oriented Write a Python program to find the mean (average) of numeric values stored in a list without using the built-in sum() function.


Answers to Competency Based Questions

A1. Output:

6
[40, 50]

Explanation:

  1. append([40, 50]) adds the list [40, 50] as a single element. List becomes [10, 20, 30, [40, 50]]. Length = 4.
  2. extend([60, 70]) adds individual elements. List becomes [10, 20, 30, [40, 50], 60, 70]. Length = 6.
  3. L[3] refers to the nested list [40, 50].

A2. Error: In the for i in L: loop, i is just a temporary copy of the value. Changing i does not change the actual list element. Correction: He must use index-based assignment.

L = [1, 2, 3]
for i in range(len(L)):
    L[i] = L[i] * 2
print(L)

A3. She should use the insert() method.

marks_list.insert(2, 85)

(Note: Index 2 corresponds to the 3rd position, since indices start at 0).

A4.

L = [10, 20, 30, 40, 50]
total = 0
count = 0

for num in L:
    total += num
    count += 1

mean = total / count
print("Mean is:", mean)