Python List

List operations

Let's focuses on manipulating elements within Python lists.

1. Adding elements:

  • append()
This method adds an element to the end of the list. It's like putting a new item at the back of your shopping list.

fruits = ["apple", "banana"]
fruits.append("cherry")  # fruits becomes ["apple", "banana", "cherry"]


  • insert(index, element)
This method inserts an element at a specific position in the list. Think of inserting an item in the middle of your shopping list.

fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "kiwi")  # fruits becomes ["apple", "kiwi", "banana", "cherry"]


2. Removing elements:

  • remove(element)
This method removes the first occurrence of a specified element from the list.

fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")  # fruits becomes ["apple", "cherry", "banana"]


  • pop(index=-1)
This method removes and returns the element at a specific position in the list. By default (-1), it removes the last element. It's like taking something out of your shopping bag.

fruits = ["apple", "banana", "cherry"]
removed_fruit = fruits.pop()  # removed_fruit will be "cherry", fruits becomes ["apple", "banana"]


3. Modifying elements by assignment

Since lists are mutable (changeable), you can modify elements directly by their index within square brackets and assigning a new value.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"  # fruits becomes ["apple", "mango", "cherry"]

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What does the append() method do in a Python list?

Adds an element to the end of the list.
Removes an element from the list.
Inserts an element at a specific position.
Sorts the list.
Check Answer

How do you insert an element at a specific position in a Python list?

Use the add() method.
Use the insert(index, element) method.
Use the append() method.
Use the remove() method.
Check Answer

What does the remove() method do in a Python list?

Removes all occurrences of the specified element.
Removes the last element from the list.
Removes the first occurrence of the specified element.
Clears the entire list.
Check Answer

What does the pop() method do in a Python list?

Removes and returns the element at the specified index.
Removes and returns the last element by default.
Adds an element to the end of the list.
Inserts an element at the specified index.
Check Answer

How can you modify an element in a Python list?

By assigning a new value to the specific index.
By using the change() method.
By using the modify() method.
By removing and re-adding the element.
Check Answer