List of strings in Python
A list of strings in Python stores multiple strings together. In this article, we’ll explore how to create, modify and work with lists of strings using simple examples.
Creating a List of Strings
We can use square brackets [] and separate each string with a comma to create a list of strings.
a = ["apple", "banana", "cherry"]
print(a)
Output
['apple', 'banana', 'cherry']
Explanation: 'a' is a list containing three string elements: "apple", "banana", and "cherry".
Note: We can also use list() constructor to create a list of strings.
Accessing Elements in a List
We can access elements in a list using their index. Python supports both positive indexing (from the start) and negative indexing (from the end).
a = ["apple", "banana", "cherry"]
# First element using positive index
print(a[0])
# Last element using negative index
print(a[-1])
# Second last element
print(a[-2])
Output
apple cherry banana
Explanation:
- Positive indexing: Starts from 0. So, a[0] retrieves "apple".
- Negative indexing: Starts from -1 for the last element. So, a[-1] retrieves "cherry" and a[-2] retrieves "banana".
Adding Elements to a List
We can add elements to a list using the append() or insert() methods.
a = ["apple", "banana"]
# Add at the end of list
a.append("cherry")
# Add at index 1
a.insert(1, "orange")
print(a)
Output
['apple', 'orange', 'banana', 'cherry']
Explanation:
- append("cherry") adds "cherry" to the end of the list.
- insert(1, "orange") places "orange" at the second position (index 1).
Removing Elements from a List
To remove elements from list, we can use remove(), pop(), or del().
a = ["apple", "banana", "cherry"]
# Remove by value
a.remove("banana")
# Remove by index
val = a.pop(1)
print(val)
# Delete first element
del a[0]
print(a)
Output
cherry []
Explanation:
- remove("banana") deletes "banana" from the list.
- pop(1) removes the second element and stores it in val.
- del a[0] deletes the first element.
Modifying Strings in a List
To modify the strings in a list we can use index to modify elements directly.
a = ["apple", "banana", "cherry"]
a[1] = "orange"
print(a)
Output
['apple', 'orange', 'cherry']
Explanation: a[1] = "orange" replaces "banana" with "orange".
Iterating through a List
We can use a for loop to iterate through all strings in the list.
a = ["apple", "banana", "cherry"]
for s in a:
print(s)
Output
apple banana cherry