Initialization of an Empty List in Python

A list is a fundamental data structure used in python that can store multiple items. An empty list is created by initializing it with square brackets but without any values inside them. Here’s how to …

Updated November 27, 2023

A list is a fundamental data structure used in python that can store multiple items. An empty list is created by initializing it with square brackets but without any values inside them. Here’s how to initialize an empty list in python.

In Python, you can declare and initialize an empty list in the following ways:

  1. Creating an Empty List: To create an empty list in Python, you need to use square brackets “[]”. However, this is just a declaration of the list. No values are contained within it.

Here’s how you do that:

empty_list = []   # This creates an empty list
print(empty_list)  # prints: []
  1. Initializing List with Values: You can also initialize a list with values by providing them inside the square brackets. Each value should be separated by a comma.

Here’s how you do that:

numbers = [1, 2, 3, 4, 5]   # This creates a list of numbers
print(numbers)  # prints: [1, 2, 3, 4, 5]
  1. List Comprehensions: You can also initialize a list with values using the list comprehension feature in Python. It’s very similar to creating an empty list and then adding elements one by one. Here’s how you do that:
even_numbers = [x for x in range(10) if x % 2 == 0]   # This creates a list of even numbers from 0 to 9
print(even_numbers)  # prints: [0, 2, 4, 6, 8]

In all cases, you can access elements in the list by using their index number. Lists are zero-indexed, meaning that the first item is at position 0 and the last one is at position len(list) - 1.

That’s it for creating an empty list in Python!

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!