Learn the fundamentals of Python lists, including creation, manipulation, indexing, and common operations. Explore practical examples and best practices.
0
for the first item.You can create a list by placing items inside square brackets []
, separated by commas.
# A list of integers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple", "banana", "cherry"]
# A list of mixed data types
mixed_list = [1, "hello", 3.14, True]
# An empty list
empty_list = []
You can access individual elements in a list using their index.
# Access the first element (index 0)
print(fruits[0]) # Output: apple
# Access the second element (index 1)
print(fruits[1]) # Output: banana
# Access the last element (index -1)
print(fruits[-1]) # Output: cherry
Since lists are mutable, you can change an element in a list by assigning a new value to a specific index.
# Change the first element of the list
fruits[0] = "orange"
print(fruits) # Output: ['orange', 'banana', 'cherry']
# Concatenation
new_list = [1, 2] + [3, 4] # [1, 2, 3, 4]
# Repetition
repeated = [0] * 3 # [0, 0, 0]
# Membership testing
if 'a' in my_list:
print("Found!")
# Length
length = len(my_list) # Number of elements
You can use a loop to iterate through all the elements in a list.
# Print each fruit in the list
for fruit in fruits:
print(fruit)
# Output:
# mango
# grape
This video covers:
This video covers:
Write a Python program that:
Example Output:
Favorite Foods: ['Pizza', 'Burger', 'Pasta', 'Ice Cream']
Second food: Burger
Write a Python program that:
Example Output:
Original List: ['Red', 'Blue', 'Green']
Updated List: ['Yellow', 'Blue', 'Green']
Write a Python program that:
Example Output:
Original List: ['Ahmed', 'Hassan', 'Omar', 'Yusuf', 'Zayd']
Third name: Omar
Updated List: ['Ahmed', 'Hassan', 'Omar', 'Yusuf', 'Bilal']