Exercises:
Exercise 1: Create a list of 5 different fruits. Use the
append()
method to add ‘mango’ to the list. Print the updated list.Hint: Remember,
append()
adds an element to the end of the list.Solution:
fruits = ['apple', 'banana', 'cherry', 'orange', 'grape'] fruits.append('mango') print(fruits)
Exercise 2: Now, add ‘kiwi’ and ‘pineapple’ to the list of fruits using the
extend()
method. Print the updated list.Hint:
extend()
can take a list as an argument.Solution:
fruits.extend(['kiwi', 'pineapple']) print(fruits)
Exercise 3: Insert ‘pear’ at the second position in the list of fruits. Print the updated list.
Hint: Remember, Python list indices start at 0.
Solution:
fruits.insert(1, 'pear') print(fruits)
Exercise 4: Remove ‘grape’ from the list of fruits. Print the updated list.
Hint: Use the
remove()
method.Solution:
fruits.remove('grape') print(fruits)
Exercise 5: Use a for loop to print each fruit in the list on a new line.
Hint: You can iterate over a list using a for loop.
Solution: