Python Programming - Long Answer Notes
Python Lists - Long Answer Format
Lists in Python - Long Answer (Theory + Examples)
Introduction to Lists:
A list in Python is a mutable, ordered collection of elements that can contain heterogeneous data types such
as integers, strings, floats, and even other lists. Lists are defined using square brackets [] or the list()
constructor. They are dynamically sized and allow duplicate values.
Characteristics of Lists:
- Mutable: Can be changed after creation.
- Ordered: Elements maintain insertion order.
- Indexed: Access elements using indexes.
- Allows duplicates: Same value can appear multiple times.
- Supports slicing: Subparts of list can be accessed.
List Creation:
a = [1, 2, 3]
b = list(["apple", "banana", "cherry"])
nested = [1, [2, 3], [4, 5]]
Processing a List:
Access: a[0] => 1
Modify: a[1] = 99
Loop: for item in a: print(item)
Finding Items with 'in' Operator:
fruits = ["apple", "banana"]
print("banana" in fruits) -> True
Built-in List Functions and Methods:
Python Programming - Long Answer Notes
- len(list): Number of elements
- append(x): Add item at end
- insert(i, x): Add x at index i
- remove(x): Remove first occurrence of x
- pop(): Remove and return last item
- index(x): First index of x
- count(x): Number of times x appears
- reverse(): Reverse list
- sort(): Sort list in place
- sum(list), max(list), min(list)
Copying Lists:
- Incorrect (alias): b = a
- Correct:
b = [Link]()
b = list(a)
b = a[:]
Important Theory Points:
- Lists are mutable and ordered
- Elements accessed using positive/negative indices
- Support slicing and iteration
- Can be nested and allow duplicates
Example:
fruits = ["apple", "banana"]
[Link]("mango")
[Link](1, "orange")
print("banana" in fruits)
print(fruits[2])
print(len(fruits))
Python Programming - Long Answer Notes
Sample Exam Question (8 marks):
Q. Explain Python lists in detail. What are the various operations that can be performed on lists with
examples?
Expected Answer:
Define list, list creation, characteristics, access/modify methods, operations (append, pop, etc.), copying,
examples, sample code.