How to Initialize List in Python

To initialize a list in Python, you can use the square brackets([]), write the list elements separated by commas inside the square brackets, and assign them to a variable.

data = [11, 19, 21, 46]

print(data)

Output

[11, 19, 21, 46]

Alternate approaches

Here are alternative approaches to initialize a list.

  1. Initialize using the list() function.
  2. Using the list comprehension.
  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

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']

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.