Lists are a fundamental data structure in Python that allow us to store and manipulate collections of data. They are ordered, mutable, and can contain elements of different data types.
Let’s explore lists and how to manipulate them:
# Creating a list
fruits = ["apple", "banana", "orange"]
# Accessing list elements
print("First fruit:", fruits[0]) # Indexing starts from 0
print("Second fruit:", fruits[1])
# Modifying list elements
fruits[2] = "grape" # Changing the value at index 2
# Adding elements to a list
fruits.append("kiwi") # Adds "kiwi" to the end of the list
fruits.insert(1, "pear") # Inserts "pear" at index 1
# Removing elements from a list
fruits.remove("banana") # Removes the element "banana"
del fruits[0] # Removes the element at index 0
# Checking the length of a list
print("Number of fruits:", len(fruits))
# Iterating over a list
for fruit in fruits:
print(fruit)
Explanation:
- We create a list
fruits
containing three elements: “apple”, “banana”, and “orange”. - We access list elements using index numbers starting from 0. For example,
fruits[0]
retrieves the first element (“apple”). - We can modify list elements directly by assigning new values to specific indices.
- We use methods like
append()
andinsert()
to add elements to the list. - We use methods like
remove()
and thedel
statement to remove elements from the list. - The
len()
function allows us to check the length (number of elements) of a list. - We can iterate over a list using a
for
loop, as demonstrated in the example.
Now it’s time for a practical task:
Task 6:
Write a Python program that creates an empty list called numbers
. Prompt the user to enter five numbers and add them to the list. Finally, print the sum of all the numbers in the list.
Once you’ve completed the task, you can proceed to the next lesson.