Notes on Lists in Python for Class 12 Computer Science

Notes on Lists in Python  for  Class  12 Computer Science

1. Definition

A list is a built-in data structure in Python used to store multiple items in a single variable. It is one of the most versatile and commonly used sequence types.

2. Key Characteristics

  • Ordered: Items hold a specific position (index).

  • Mutable: You can add, remove, or change items after the list is created.

  • Heterogeneous: Can store elements of different data types (integers, strings, booleans, even other lists) together.

  • Allow Duplicates: The same value can appear multiple times.


3. Syntax & Creation

Lists are created using square brackets [], separating elements with commas.

Python
# Empty List
my_list = []

# Integers
numbers = [10, 20, 30, 40]

# Mixed Data Types
mixed = [1, "Hello", 3.14, True]

# Nested List (List inside a list)
nested = [1, [2, 3], 4]

4. Indexing and Slicing

Python uses zero-based indexing. You can access elements from the start (positive index) or the end (negative index).

  • Accessing Elements:

    • numbers[0] First item.

    • numbers[-1] Last item.

  • Slicing (list[start:stop:step]):

    • numbers[1:3] Items from index 1 up to (but not including) 3.

    • numbers[::-1] Reverses the list.


5. Common List Methods

MethodDescriptionExample
append(x)Adds an item x to the end.lst.append(5)
insert(i, x)Inserts item x at index i.lst.insert(1, "Hi")
extend(seq)Adds all elements of a sequence to the end.lst.extend([6, 7])
remove(x)Removes the first occurrence of item x.lst.remove(5)
pop(i)Removes and returns item at index i (default last).lst.pop()
index(x)Returns the index of the first item with value x.lst.index("Hi")
count(x)Returns how many times x appears.lst.count(5)
sort()Sorts the list in ascending order (modifies original).lst.sort()
reverse()Reverses the order of elements (modifies original).lst.reverse()

6. Modifying Lists

Because lists are mutable, you can change them directly using their index.

Python
fruits = ["apple", "banana", "cherry"]

# Change an item
fruits[1] = "mango"  
# Result: ["apple", "mango", "cherry"]

# Delete an item using 'del' keyword
del fruits[0]
# Result: ["mango", "cherry"]

7. List Comprehension

A concise way to create lists based on existing lists. It is often faster and more readable than a for loop.

Syntax: [expression for item in iterable if condition]

Python
# Standard Loop way
squares = []
for x in range(5):
    squares.append(x**2)

# List Comprehension way (One-liner)
squares = [x**2 for x in range(5)] 
# Result: [0, 1, 4, 9, 16]

8. Essential Built-in Functions

  • len(list): Returns the number of items.

  • min(list): Returns the smallest item.

  • max(list): Returns the largest item.

  • sum(list): Returns the sum of all items (if numbers).

  • sorted(list): Returns a new sorted list (does not modify the original).



Comments

Popular Posts