2.6. Lists#
2.6.1. What is a List?#
Imagine you have a collection of items, like a grocery shopping list. In real life, you might write down each item you need—apples, bread, milk—on a piece of paper, one after another. In Python, a list is just like that shopping list, but it’s a way to store a collection of items in a single variable.
Lists are useful when you want to group multiple items together. Instead of creating separate variables for each item, you can store them all in one place, making your code easier to manage.
2.6.2. How Do Lists Work?#
A list is like a box that can hold multiple values, and you can access any of these values whenever you need them. Lists can store numbers, words, or even other lists! You create a list using square brackets [] and separate each item with a comma.
For example, if you want to store the names of fruits, you could write:
fruits = ["apple", "banana", "cherry"]
This list contains three items: “apple
,” “banana
,” and “cherry
”
The grammar rules of a programming language are rigid. In Python, the *
symbol cannot appear twice in a row. The computer will not try to interpret an expression that differs from its prescribed expression structures. Instead, it will show a SyntaxError
error. The Syntax of a language is its set of grammar rules, and a SyntaxError
indicates that an expression structure doesn’t match any of the rules of the language.
2.6.2.1. Creating Lists#
Let’s start by learning how to create lists in Python. Lists can contain any number of items, even none!
Example 1: A List of Numbers
numbers = [1, 2, 3, 4, 5] #holds five numbers
Example 2: A List of Words
words = ["hello", "world", "python"] #holds three words
Example 3: An Empty List
empty_list = [] #This is an empty list with no items in it, but you can add items later.
2.6.2.2. Accessing Items in a List#
Lists store items in order, and each item has a specific position, known as its index. In Python, indexing starts at 0, not 1. This means that the first item in a list is at index 0, the second item is at index 1, and so on.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[2]) # Output: cherry
apple
banana
cherry
In this example, fruits[0]
gives us the first item in the list, which is “apple.”
2.6.2.3. Negative Indexing#
You can also use negative indexing to access items from the end of the list. The last item is at index -1
, the second-to-last item is at -2
, and so on.
print(fruits[-1]) # Output: cherry
print(fruits[-2]) # Output: banana
cherry
banana
But the power of lists doesn’t end here! As you continue to learn more about Python, you’ll encounter other tools and libraries that build upon the concept of lists. For example, Pandas, a popular library for data analysis, uses lists to create DataFrames and Series. DataFrames and Series are like advanced lists or tables, making it easier to analyze, manipulate, and visualize large datasets.