Lists
Swipe to show menu
Instead of creating separate variables for many values, you can use a list to store them all together.
In Python, a list is an ordered and flexible structure built into the language. It's one of the most commonly used data types for grouping multiple values.
Creating a List
Lists are defined with square brackets, separating items by commas: [1, 2, 3].
They can be empty [], hold strings like ["apple", "banana"], or even mix types [42, "hello", True].
Lists are useful for data that may grow, change, or be processed with loops.
Accessing Items
List elements are accessed by index, starting at 0.
For example, fruits[0] is "apple", and fruits[1] is "banana".
Negative indexes count from the end: fruits[-1] is "cherry", and fruits[-2] is "banana".
Modifying Lists
Lists are flexible because you can change them after creation.
- Update by index:
cart[0] = "mango"; - Add with
.append():cart.append("orange"); - Remove last item with
.pop(), or a specific one with.remove("apple").
This makes lists useful for dynamic data.
Summary
- Lists are used to store multiple values β all in one variable;
- You can access each item by its index β and also update, add, or remove items;
- Lists are great for dynamic data β like queues, collections, and search results;
- They are flexible, readable, and essential for many real-world tasks in Python.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat