How do you append (or add) new values to an already created list in Python? I will show you how in this article.
But first things first...
What is a
List in Python?
List is a data type that allows you to store multiple values of either the same or different types in one variable.
Take a look at the example below:
age = 50 name = "Python" isRunning = False
In this code,
isRunning only hold one value each, of the
boolean data types, respectively.
Let's say you wanted to store all the things you bought in the market using this approach:
item1 = "banana" item2 = "apple" item3 = "orange"
Creating three separate variables for related items may not be the best approach.
With lists, you can create a variable that holds multiple values. Here's how:
numbers = [1, 2, 3] strings = ["list", "dillion", "python"] mixed = [10, "python", False, [40, "yellow"]]
numbers variable is a list containing three number values.
strings variable is a list containing three string values.
mixed variable is a list containing a number, a string, a boolean, and even another list.
So for the items you bought at the market, you can store them like this:
items = ["banana", "apple", "orange"]
And you can access each item using its index position in the list, starting from 0 (as lists are zero-indexed in Python):
print(items, items, items) # banana apple orange
How to Append Data to a List in Python
We've briefly seen what lists are. So how do you update a list with new values? Using the
append method receives one argument, which is the value you want to append to the end of the list.
Here's how to use this method:
mixed = [10, "python", False] mixed.append(40) print(mixed) # [10, 'python', False, 40]
append method, you have added
40 to the end of the
You can add any data type you want, including other lists:
mixed = [10, "python", False] mixed.append([True, "hello"]) print(mixed) # [10, 'python', False, [True, 'hello']]
Lists are useful for creating variables that hold multiple values (especially when these values are related)
Lists have many methods in Python that you can use to modify, extend, or reduce the lists. In this article, we've looked at the
append method which adds data to the end of the list.