Creating Lists

Python offers a variety of ways for us to create lists, such as list literals, list constructors, and list comprehensions.

List literals

A list literal is the simplest way to create a list. We just need to add comma-separated values enclosed in square brackets [].

Syntax

[element1, element2, … ]
my_list = [1, 5, 10, 15, 20]
print(my_list)
print([True, False, False, "1"])

List constructor

A list constructor involves the use of the class constructor list() to create a list object. To create a list using this method, the values to be included in the list are passed in the constructor, which is enclosed by square brackets [].

The following code uses the constructor to create a list containing three strings, “Lists”, “are” and “useful”, respectively.

my_list = list(["Lists", "are", "useful!"])
print(my_list)

Note: If list() is called without any parameters, an empty list will be returned.

List comprehension

List comprehensions are one of the most interesting things we can do with a list! The section on list comprehensions gives a detailed guide on how to use them.

The following code creates my_list and initializes the list with the numbers from 1 to 5 (i.e. 1, 2, 3, 4, and 5).

my_list = [num for num in range (1,6)]
print(my_list)