Creating and Using Lists in Python

In programming, we often have data that we want to store together. If the data is numerical, it’s usually stored in lists in Python. …

Updated October 10, 2023

In programming, we often have data that we want to store together. If the data is numerical, it’s usually stored in lists in Python.

In python, you can create an empty list by writing “list = []”. To add items to a list, you use “.append()” method. Here’s how:

# Creating an Empty List
numbers_list = []

# Adding Elements to the List
for i in range(10):
    numbers_list.append(i)

print(numbers_list)  # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In the code above, we created an empty list and filled it with numbers from 0 to 9 by appending them one at a time.

Lists in Python can hold multiple data types, not just numbers. You can also use “.insert()” method to insert an item at a specific index. Here’s how:

# Creating an Empty List
letters_list = []

# Adding Elements to the List
for i in range(3):
    letters_list.append('a' + str(i))
    
# Inserting at a Specific Index
letters_list.insert(0, 'z')
print(letters_list)  # Output: ['z', 'a0', 'a1', 'a2']

In the code above, we created an empty list and filled it with letters from ‘a0’ to ‘a2’. We then inserted an element at index 0 using “.insert()” method.

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!