Creating Lists
Explore how to create and initialize lists in Python using different methods including literals list constructors and list comprehensions. Understand the syntax and practical uses to efficiently store and manipulate data within your programs.
We'll cover the following...
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, … ]
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.
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).