A list of strings is a very common data structure to use in your Python programs. With this tutorial, you will learn to create and manipulate lists of strings in Python.
The syntax to create a list of strings is the standard syntax to create any lists in Python, you will specify the strings in the list comma-separated within square brackets. You can use all the list methods to work on a list of strings either if you want to add an element to it, remove an element from it, or update an element.
Let’s start by creating a list of strings!
How to Create a List of Strings in Python
Open the Python shell and start creating a list of lists straight away.
First of all, specify the name of the variable for your list followed by the equal sign. Then on the right side of the equal sign, specify the list by doing the following:
- Open a square bracket to start the list.
- Specify the elements in the list of strings separated by commas. Specify every element within single or double quotes considering that every element of the list is a string.
- Close the square bracket to end the list.
>>> animals = ['dog','cat','tiger','lion']
As you can see from the code above, you can use the type() built-in function to confirm that the variable you have created is a list.
How to Access an Element in a Python List of Strings
An index is used in lists to access each element of the list, the value of the index starts from zero and the highest value is the number of elements in the list minus one.
To print the value of an element in a list of strings based on the index you can use the following syntax
For instance, to print the first element of the list animals you can use the following Python code:
And to print the last element: