List Manipulation Based on CBSE Curriculum Class 11
Introduction
- Python lists: containers for collections of values.
- Lists are mutable; values can be changed without creating a new list.
- Lists are sequences like strings and tuples but mutable.
List Creation
- Lists store values of any kind and are represented by square brackets
[].
- Examples:
[]: Empty list
[1, 2, 3]: List of integers
[1, 2.5, 5.6, 9]: List of numbers (integers and floats)
[a, b, c]: List of characters
[a, 1, b, 3.5, zero]: Mixed values list
[one, two, three]: List of strings
- Creation methods:
L = []: Empty list
L = list(): Using the list() function
even = [0, 2, 4,..., 20]: Long list
L = [3, 4, [5, 6], 7]: Nested list
- Using
eval(input()) to generate lists from user input.
Accessing a List
- Lists are sequences similar to strings and support indexing (forward and backward).
- Forward indexing: From 0 to n-1
- Backward indexing: From -n to -1
- Access methods:
len(): Returns the length of a list.
L[i]: Accesses value at index i.
L[i:j]: Returns a new list from index i to j-1.
- Membership operators
in and not in function similarly as in other sequences.
+ operator joins lists, * operator repeats lists.*
Difference Between List and String
- Lists are mutable; strings are immutable.
- Values in a string cannot be changed, while values in a list can.
Traversal of a List
- Traversal involves accessing and processing each element.
- Achieved using a
for loop.
Comparison of Lists
- Relational operators compare lists lexicographically.
- Types and elements must be similar for valid comparison.
List Operations
- Operations include joining (+), replicating (*), and slicing.
- List slicing syntax:
seq = list[start:stop] or seq = list[start:stop:step].*
List Manipulation
- Appending:
list.append(item).
- Updating:
list[index] = new_value.
- Deletion:
del list[index] deletes an element.
del list deletes the entire list.
pop() deletes and returns an element from a specified index.
List Functions and Methods
- List.index(item): Returns the index of an item.
- List.append(item): Adds item to the end.
- List.extend(list): Appends another list.
- List.insert(pos, item): Inserts item at position.
- List.pop(index): Removes and returns item at index.
- List.remove(value): Deletes first occurrence of a value.
- List.clear(): Empties the list.
- List.count(item): Counts occurrences of an item.
- List.reverse(): Reverses the list.
- List.sort(): Sorts the list; use
list.sort(reverse=True) for descending order.
Important Notes
Presented by: Neha Tyagi, KV 5 Jaipur II Shift