Working with Lists in Python
Understanding how to manipulate lists in Python
Lists are one of the built-in data structures of Python. They are ordered, mutable sequences used to store multiple elements in a single variable.
Ordered means that the elements in the list occupy a specific position, which is identified by their index.
Mutable means that we can modify lists by changing, adding or removing elements.
In this post, we will learn how to create and manipulate lists.
Creating lists
Lists can be created by including the elements between square brackets [] or by using the list() function.
Independently by the procedure chosen, the elements in a list must be separated by commas.
# Create a list of cities using sqare brackets.
cities = [“London”, “Rome”, “Washington", “Paris”]
# Let's print cities.
print(cities)
['London', 'Rome', 'Washington', 'Paris']
We can obtain the same result by using the list() function.
cities = list(("London", "Rome", "Washington", "Paris"))
# Note the use of the double parentheses.
print(cities)
['London', 'Rome', 'Washington', 'Paris']