Explore String Lists
In this step, you will learn about string lists in Python. A string list is simply a list where each element is a string. Lists are a fundamental data structure in Python, used to store an ordered collection of items. Understanding how to work with lists of strings is crucial for many programming tasks, such as processing text data, manipulating filenames, and more.
First, let's create a simple string list. Open the VS Code editor in the LabEx environment. Create a new file named string_list.py
in the ~/project
directory.
## Create a list of strings
my_list = ["apple", "banana", "cherry"]
## Print the list
print(my_list)
Save the file. Now, open a terminal in the ~/project
directory and run the script:
python string_list.py
You should see the following output:
['apple', 'banana', 'cherry']
Now, let's explore some common operations you can perform on string lists. You can access individual elements of the list using their index. Remember that Python uses zero-based indexing, meaning the first element has an index of 0.
Add the following code to your string_list.py
file:
## Accessing elements by index
first_element = my_list[0]
second_element = my_list[1]
print("First element:", first_element)
print("Second element:", second_element)
Run the script again:
python string_list.py
You should see the following output:
['apple', 'banana', 'cherry']
First element: apple
Second element: banana
You can also modify elements in the list:
## Modifying an element
my_list[1] = "grape"
print(my_list)
Run the script again:
python string_list.py
You should see the following output:
['apple', 'banana', 'cherry']
First element: apple
Second element: banana
['apple', 'grape', 'cherry']
Finally, you can add new elements to the list using the append()
method:
## Adding an element
my_list.append("orange")
print(my_list)
Run the script one last time:
python string_list.py
You should see the following output:
['apple', 'banana', 'cherry']
First element: apple
Second element: banana
['apple', 'grape', 'cherry']
['apple', 'grape', 'cherry', 'orange']
This demonstrates the basic operations you can perform on string lists in Python. In the next steps, you will learn more advanced techniques for working with lists.