Python – List of Strings

List of Strings in Python

Python - List of Strings

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)
Run Code Copy

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)
Run Code Copy

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])
Run Code Copy

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)
Run Code Copy

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)
Run Code Copy

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
Run Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍