Python Lists
Definition: A list in Python is a collection that is ordered, mutable, and allows duplicate
elements. It is one of the most versatile data structures.
Syntax:
my_list = [1, 2, 3, 4, 'hello', 5.6]
Lists can hold different data types including integers, floats, strings, and even other lists.
Access List Items
Accessing Elements: Use indices to access list items. The first item has an index of 0, the
second item is 1, and so on.
Example:
my_list = ['apple', 'banana', 'cherry']
print(my_list[0]) # Output: apple
numbers = [10, 20, 30, 40, 50]
# Positive indexing (starts at 0)
first_item = numbers[0] # 10
second_item = numbers[1] # 20
# Negative indexing (starts at -1)
last_item = numbers[-1] # 50
second_last = numbers[-2] # 40
# Slicing [start:end:step]
subset = numbers[1:4] # [20, 30, 40]
every_second = numbers[::2] # [10, 30, 50]
reversed_list = numbers[::-1] # [50, 40, 30, 20, 10]
Change List Items
Modify Elements: Lists are mutable, meaning you can change their content.
Example:
my_list[1] = 'orange'
print(my_list) # Output: ['apple', 'orange', 'cherry']
numbers = [1, 2, 3, 4, 5]
# Change single item
numbers[0] = 10
# Change multiple items using slice
numbers[1:4] = [20, 30, 40]
# Change items using negative index
numbers[-1] = 50
# Change items with step
numbers[::2] = [100, 300, 500] # Changes every second element
Add List Items
Append: Add an item to the end of the list.
Example:
numbers = [1, 2, 3]
# append() - Add single item to end
numbers.append(4) # [1, 2, 3, 4]
# insert() - Add item at specific position
numbers.insert(1, 1.5) # [1, 1.5, 2, 3, 4]
# extend() - Add multiple items to end
numbers.extend([5, 6, 7]) # [1, 1.5, 2, 3, 4, 5, 6, 7]
# Using + operator
new_list = numbers + [8, 9]
Remove List Items
Remove by Value:
my_list.remove('banana')
Remove by Index:
my_list.pop(2)
Clear: Remove all items.
my_list.clear()
Loop Lists
For Loop:
for item in my_list:
print(item)
While Loop:
i=0
while i < len(my_list):
print(my_list[i])
i += 1
List Comprehension
Definition: A concise way to create lists using a single line of code.
Example:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Sort Lists
Ascending Order:
my_list.sort()
Descending Order:
my_list.sort(reverse=True)
Custom Sorting:
my_list.sort(key=len)
Copy Lists
Using copy():
new_list = my_list.copy()
Using List Slicing:
new_list = my_list[:]
Join Lists
Concatenate:
combined_list = list1 + list2
Extend Method:
list1.extend(list2)
List Methods
Common Methods:
- append(): Adds an element at the end.
- insert(): Inserts an element at a specific position.
- remove(): Removes an element by value.
- pop(): Removes an element by index.
- index(): Returns the index of the first matching element.
- count(): Counts occurrences of an element.
- reverse(): Reverses the list.
- sort(): Sorts the list.
List Exercises
1. Create a list of the first 10 natural numbers and print the even numbers only.
2. Write a program that removes duplicates from a list.
3. Write a Python program that merges two lists and sorts them.
4. Use list comprehension to generate a list of squares for numbers from 1 to 20.