Python - List of Strings
List of Strings in Python
In Python, List of Strings is a list which contains strings as its elements.
In this tutorial, we will learn how to create a list of strings, access the strings in list using index, modify the strings in list by assigning new values, and traverse the strings in list in a loop using while, for.
Create List of Strings
To create a list of strings, assign the comma separated string values enclosed in square brackets.
Python Program
list_of_strings = ['apple', 'banana', 'mango']
print(list_of_strings)
Output
['apple', 'banana', 'mango']
We can also use list() constructor to create a list of strings as shown below.
Python Program
list_of_strings = list(['apple', 'banana', 'mango'])
print(list_of_strings)
Access Strings in List of Strings
To access items in list of strings, we can use index. Index starts from 0, and increments by one for subsequent elements.
Python Program
list_of_strings = ['apple', 'banana', 'mango']
print(list_of_strings[0])
print(list_of_strings[1])
print(list_of_strings[2])
Output
apple
banana
mango
Modify Strings in List of Strings
To modify items in list of strings, we can use index similar to as how we accessed strings in the above example. We have to use assignment operator and assign a new value to the element in list referenced by index.
Python Program
list_of_strings = ['apple', 'banana', 'mango']
list_of_strings[1] = "orange"
print(list_of_strings)
Output
['apple', 'orange', 'mango']
Traverse Strings in List of Strings
Strings in List of Strings are ordered collection of items. So, we can use any looping statement: while, for loop.
In the following example, we will use for loop to traverse each string in list of strings.
Python Program
list_of_strings = ['apple', 'banana', 'mango']
for string in list_of_strings:
print(string)
Output
apple
banana
mango
In the following example, we will use while loop to traverse each string in list of strings.
Python Program
list_of_strings = ['apple', 'banana', 'mango']
i = 0
while i < len(list_of_strings):
print(list_of_strings[i])
i += 1
Output
apple
banana
mango
Summary
In this tutorial of Python Examples, we learned how to create, access, modify and iterate for a list of strings.