Lately, i have put some good focus on automating some mundane tasks such as working with files, creating reports and presentations. This gave me a good opportunity to write lots of Python code. In the upcoming weeks i would like to share some tutorials on Python fundamentals to help readers get started with Python.
Lists are probably the most basic and useful data construct in Python. Lists are ordered sequences of elements (or items). Lists can contain strings, integers, floating point numbers, tuples, dictionaries or other lists.
Provided you have an existing list, containing the content of a CSV / text file for example, the question is how to add additional elements to the list.
Adding items to a Python list
- Open your favorite Python editor. If you are just starting out you might want to try the web based repl.it site.
- If not available yet, create a new list.
- Use the Append method to add items to the end of the list or Insert to add items at a specific sequence index in the list.
Creating your list
Let’s assume that we’ll create the languages list containing programming languages names.
We’ll then also define a string that we would like to include in the list.
Appending elements to a list
languages.append(new_lang) print (languages)
# instead of appending a variable, we'll type a string languages.append("Python") print (languages)
Inserting items to Python listSo far, we have seen that when using Append, we can get a new value at the end of the list. But what if we want to insert an item to the beginning of the list or at any other index ? For that we are going to use the Insert method. The Python list Insert method takes a couple parameters:
Our code will look as following:
The result will be:
In a similar fashion you can insert not only strings but any other variables into your list.
Using loops to update listsLet’s assume now that i want to use a loop to append the numbers 0-9 into a newly created list. We’ll use the following Python code.
The result will looks as following:
# first we'll define an empty list numbers =  # We'll then loop and append the list items for item in range(10): numbers.append(item) # Lastly, we'll print the list print(numbers)
An obviously way more elegant solution is provided using a list comprehension:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers = [item for item in range(10)] print(numbers)