10. Python List

Quiz: 0/5

Imagine you’re creating a shopping list. Instead of juggling multiple notes for each item, you write everything on a single list. In Python, lists serve the same purpose—they help you organize multiple values in one neat package. Whether it’s tracking groceries, expenses, or tasks, lists make it easy to store, update, and process information efficiently.

What is a list?

A list in Python is a collection of items, enclosed in square brackets [ ] and separated by commas. Lists can hold any data type—strings, numbers, or even other lists.

shopping_list = ["apples", "bananas", "carrots", "bread"]

Here, shopping_list contains four items. Think of a list as a flexible container for organizing multiple values.

Accessing items in a list

Each item in a list is assigned a position, or index, starting from 0. You can use the index to retrieve specific items:

print(shopping_list[0])  # Output: "apples"
print(shopping_list[2])  # Output: "carrots"
  • shopping_list[0]: Gets the first item, "apples".
  • shopping_list[2]: Gets the third item, "carrots".

Modifying a list

Lists are dynamic, allowing you to easily change their content.

1. Changing an item

Update an item by accessing its index and assigning a new value:

shopping_list[1] = "oranges"
print(shopping_list)  # Output: ["apples", "oranges", "carrots", "bread"]

2. Adding items

Use append() to add an item to the end of the list:

shopping_list.append("milk")
print(shopping_list)  # Output: ["apples", "oranges", "carrots", "bread", "milk"]

3. Removing items

  • remove(): Deletes an item by its value.
  • pop(): Removes an item by its index (or the last item if no index is given).
shopping_list.remove("carrots")
print(shopping_list)  # Output: ["apples", "oranges", "bread"]

shopping_list.pop(1)
print(shopping_list)  # Output: ["apples", "bread"]

Looping through a list

Use loops to process each item in a list:

for item in shopping_list:
    print("I need to buy:", item)

Output:

I need to buy: apples  
I need to buy: bread

This for loop goes through each item in shopping_list and prints it.

Useful list functions

Python provides many built-in functions to work with lists efficiently:

len(): Counts the number of items in the list.

print(len(shopping_list))  # Output: 2

sort(): Sorts the list in ascending order.

shopping_list = ["bananas", "apples", "carrots"]
shopping_list.sort()
print(shopping_list)  # Output: ["apples", "bananas", "carrots"]

reverse(): Reverses the order of items.

shopping_list.reverse()
print(shopping_list)  # Output: ["carrots", "bananas", "apples"]

sum(): Adds up all the numbers in a list.

expenses = [20, 15, 30, 10]
print(sum(expenses))  # Output: 75

Examples

1. Managing a To-do list

to_do_list = ["study Python", "buy groceries", "exercise"]

# Add a task
to_do_list.append("call mom")
print(to_do_list)  # Output: ["study Python", "buy groceries", "exercise", "call mom"]

# Remove a task
to_do_list.remove("exercise")
print(to_do_list)  # Output: ["study Python", "buy groceries", "call mom"]

2. Calculating total expenses

expenses = [50, 25, 75]

# Calculate total
total = sum(expenses)
print("Total expenses:", total)  # Output: 150

Why Use Lists?

Lists are flexible and essential for managing groups of related data. Whether you’re organizing items, processing user input, or building advanced applications, lists are a must-know tool in Python. With functions like append(), remove(), and sort(), you can handle data effortlessly.

Conclusion

Lists in Python are like a Swiss Army knife—they allow you to organize, manipulate, and process data with ease. Mastering lists unlocks powerful capabilities for building efficient and dynamic programs.

Start experimenting with lists today to simplify your coding journey!

Hands-On Practise

Exercise: Grocery list manager

Objective:

Simulate a grocery list manager with operations like adding, removing, sorting, and displaying the list.

Instructions:

  1. Create a grocery list with at least 5 items (e.g., ["apples", "bananas", "carrots", "bread", "milk"]).
  2. Perform the following operations:
    • Add "oranges" to the list.
    • Remove "bread" from the list.
    • Display the list.
    • Sort the list alphabetically and display it.
    • Show the total number of items in the list.
Output:

Quizzes: 0/5

Question 1:

Which function is used to add an item to the end of a Python list?

  • insert()
  • append()
  • add()
  • extend()

Question 2:

How do you access the first item in a Python list?

  • shopping_list[0]
  • shopping_list[1]
  • shopping_list[-1]
  • shopping_list.first()

Question 3:

Which function is used to remove an item by its value from a Python list?

  • remove()
  • pop()
  • delete()
  • discard()

Question 4:

What does the sort() function do to a Python list?

  • Reverses the order of the list
  • Sorts the list in ascending order
  • Adds new items to the list
  • Counts the number of items in the list

Question 5:

Which function is used to find the total number of items in a Python list?

  • count()
  • len()
  • total()
  • size()

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonIntroduction to StringsNext lessonTuples in Python