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 items: "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 this code, 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.

These are just a few basic operations you can perform with lists in Python. There are many more methods and functionalities available for working with lists, such as sorting, slicing, and looping through the items.