Lists

A list is a collection of items that are ordered and changeable. It is one of the most commonly used data structures in Python. Think of a list as a container that can hold multiple values.

To create a list, you use square brackets [] and separate the items with commas. Here's an example:

fruits = ["apple", "banana", "orange"]

In this example, we created a list called fruits that contains three strings: "apple", "banana", and "orange". The order of the items in the list is preserved.

You can access individual items in a list by their index. The index starts from 0 for the first item, 1 for the second item, and so on. For example:

print(fruits[0])  # Output: "apple"
print(fruits[1])  # Output: "banana"

In this code, we use square brackets after the list name to access specific items. fruits[0] gives us the first item in the list, which is "apple", and fruits[1] gives us the second item, which is "banana".

You can also change the value of an item in a list by assigning a new value to its index. For example:

fruits[2] = "grape"
print(fruits)  # Output: ["apple", "banana", "grape"]

In the code above, we assign the value "grape" to the third item in the list (fruits[2]). After this change, the list will be ["apple", "banana", "grape"].

Lists in Python are also dynamic, which means you can add or remove items from them. Here are a few examples:

fruits.append("kiwi")  # Add an item to the end of the list
print(fruits)  # Output: ["apple", "banana", "grape", "kiwi"]

fruits.remove("banana")  # Remove a specific item from the list
print(fruits)  # Output: ["apple", "grape", "kiwi"]

In the first example, we use the append() method to add the item "kiwi" to the end of the list. In the second example, we use the remove() method to remove the item "banana" from the list.

Lists allow us to store multiple values and access them using their index. If you want to store key-value pairs (e.g. name = John, age = 15), use a dictionary instead.