To initialize a list in Python, you can use the square brackets([]) and write the list elements separated by commas inside the square brackets and assign it to a variable.
Example
data = [11, 19, 21, 46]
print(data)
Output
[11, 19, 21, 46]
Alternate approaches
There are the following alternative approaches to initialize a list.
- Method 1: Initialize using the list() function.
- Method 2: Using the list comprehension.
- Method 3: Using list multiplication.
Method 1: Initialize a list using the list()
Python list() function creates the list from the iterable object. An iterable may be a container, a sequence that supports iteration, or an iterator object. If no parameter is specified, then a new empty list is created.
data = list()
print(data)
Output
[]
Let’s create an empty list using [] and list() functions and compare its values.
data = list()
info = []
print(data == info)
Output
True
These first two approaches return the same result: an empty list.
There are no standards for when it is best to use either of these methods, but generally speaking, the blank square brackets ( [ ] ) approach is used because it is more instructive and concise.
Method 2: Initialize a List Using List Comprehension
Using a list comprehension approach, you can also initialize the list with default values. In Python, list comprehension is the technique that allows us to create lists using the existing iterable object, such as a list or the range() statement.
List comprehension is a handy way to define a list based on an iterator because it is elegant, simple, and widely recognized.
Syntax of List comprehension
*result* = [ *transform* *iteration* *filter* ]
Now, let's see the following example.
data = [i for i in range(10)]
print(data)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Now, from the above syntax, let’s break down the code.
result = data – Returned list.
transform = i – The items of the list.
iteration = for i in range(10)
filter = we have not defined but a generally if-else statement.
Using the list comprehension, we have initialized the list with 10 items from 0 to 9.
Method 3: Using list multiplication
Another approach for initializing the list with multiple values is list multiplication.
This approach allows us to create a list with a specific number of predefined values.
data = ['x'] * 10
print(data)
Output
['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x']
Our program has created a list of ten values from the output. We have used the multiplication syntax to declare the list with ten values on the first line.
The value we use for each item in the list is ‘x’ or whatever element you add. Then, we use the print() method to print the list to the console.
Conclusion
Initializing the list is a core part of working with lists. This example discussed initializing the empty lists using the square brackets[ ] and the list() method.
We have also discussed using the list comprehension list multiplication techniques to create a list containing a certain number of values.