Python Lists
PythonLists are ordered, mutable collections. They're the most used data structure in Python.
Key Points
- Lists use square brackets
[] - Indexing starts at
0 - Lists are mutable — you can change them
- Common methods:
append(),remove(),sort(),pop() - Use
len()to get the list size
Example — PYTHON
# Creating a list
fruits = ["Mango", "Banana", "Apple", "Grapes"]
print(fruits)
# Accessing elements
print(fruits[0]) # First item
print(fruits[-1]) # Last item
# Slicing
print(fruits[1:3]) # ["Banana", "Apple"]
# Modifying
fruits.append("Orange")
fruits.remove("Banana")
print(fruits)
# Sorting
numbers = [45, 12, 89, 3, 67]
numbers.sort()
print(f"Sorted: {numbers}")
# List comprehension
squares = [x**2 for x in range(1, 6)]
print(f"Squares: {squares}")
# Useful functions
marks = [78, 92, 65, 88, 71]
print(f"Total: {sum(marks)}")
print(f"Average: {sum(marks)/len(marks)}")
print(f"Highest: {max(marks)}")
print(f"Lowest: {min(marks)}") Result
['Mango', 'Banana', 'Apple', 'Grapes']
Mango
Grapes
['Banana', 'Apple']
['Mango', 'Apple', 'Grapes', 'Orange']
Sorted: [3, 12, 45, 67, 89]
Squares: [1, 4, 9, 16, 25]
Total: 394
Average: 78.8
Highest: 92
Lowest: 65
Mango
Grapes
['Banana', 'Apple']
['Mango', 'Apple', 'Grapes', 'Orange']
Sorted: [3, 12, 45, 67, 89]
Squares: [1, 4, 9, 16, 25]
Total: 394
Average: 78.8
Highest: 92
Lowest: 65