How to Add Data to a List in Python?

A List is a data structure that allows to store multiple values in a single variable in Python. A single Python List can store data of different data types separated by comma within brackets.

Syntax

variable_name = [item1, item2, item3, item4]

Adding String values to a List in Python

The following example code shows how to store string items to a list in Python:


# creating a list variable
x_list = []

# adding string items to the list
x_list.append("Orange")
x_list.append("Apple")
x_list.append("Mango")
x_list.append("Papaya")

# accessing each item from the list
for i in x_list:
    print(i)

The above code will generate the following output:

Orange
Apple
Mango
Papaya

Adding Integer values to a List in Python

The following example code shows how to store integer items to a list in Python:


# creating a list variable
x_list = []

# adding data of integer type to the list
x_list.append(1)
x_list.append(2)
x_list.append(3)
x_list.append(4)
x_list.append(5)
x_list.append(6)
x_list.append(7)
x_list.append(8)
x_list.append(9)

# accessing each item from the list
for i in x_list:
    print(i)

The above code will generate the following output:

1
2
3
4
5
6
7
8
9

Adding Data of Different Data Types to a List in Python

The following example code shows how to add data of different data types to a single list variable in Python:


# creating a list variable
x_list = []

# adding data of different data types to the list
x_list.append("Orange")
x_list.append("Ball")
x_list.append(5)
x_list.append(7)
x_list.append(9.70)
x_list.append(True)
x_list.append(False)

# accessing each item from the list
for i in x_list:
    print(i)

The above code will generate the following output:

Orange
Ball
5
7
9.7
True
False

Adding Dictionaries to a List in Python

Dictionaries are used for storing data in key value pairs. The following example code shows how to store dictionaries in a list:



# creating dictionaries
item1 = {
    'first_name': 'Tom',
    'last_name': 'A',
    'id': 1,
    'is_active': True
}

item2 = {
    'first_name': 'Jeni',
    'last_name': "B",
    'id': 2,
    'is_active': True
}

# creating a list variable
x_list = []

# adding dictionary items to the list
x_list.append(item1)
x_list.append(item2)

# accessing each item from the list
for i in x_list:
    print(i['first_name'])
    print(i['last_name'])
    print(i['id'])
    print(i['is_active'])
    print("---------------------")

The above code will generate the following output:

Tom
A
1
True
---------------------
Jeni
B
2
True
---------------------