Change language

Python initialize list

| | |

A Python list is an ordered collection of values. The list can contain different types of values. The list is a floating (floating) container. This means we can insert, delete or modify existing values.

Python’s list represents the mathematical concept of a finite sequence. List values ​​are called items or items. A Python list can contain the same value multiple times, unlike set. Each instance is treated as a different item.

To initialize a list in Python, assign one with brackets, initialize with the list () function, create an empty list with multiplication, or use a comprehension list. The most common way to declare a list in Python is to use square brackets.

A list is a Python data structure that contains an ordered sequence of zero or more items. Lists in Python are mutable, which means they can be modified. They can contain any type of data, such as a string or a dictionary.

When you start working with lists, you may ask: How do I initialize a list in Python? In other words: How do I create a Python list?

This tutorial will answer that question and break down the ways you can initialize a list in Python. We’ll go over the basics of lists and how you can initialize a list using square brackets, list (), list multiplication, and list comprehension.

Python List Refresher

Lists store zero or more items. Each item in a list is called an item. Lists are often called Python arrays.

In Python, the items in a list are separated by commas, and the list itself is enclosed in square brackets. Here is an example of a list in Python:

jobs = [‘Software Engineer’, ‘Web Developer’, ‘Data Analyst’]

How to Create a List in Python

You can initialize a list in Python with square brackets, the list () method, list multiplication, and list comprehension.

You can use square brackets to initialize an empty list or a list that contains some default values. The list () method works the same as square brackets. However, you must put brackets and a list of items in the list () method if you want to add some initial values.

With list multiplication, you can create a new list that repeats items from an existing list. With list comprehension, you can create a new list from the content of an existing list.

Python Create List: Square Brackets

You can use square brackets or the list () method to initialize an empty list in Python. In this tutorial, we will focus on how you can use square brackets or the list () method to initialize an empty list.

If you want to create an empty list with no values, there are two ways to declare your list. First, you can declare a list with no values ​​by specifying a series of brackets with no component values. Here is an example of this syntax:

jobs = []
print(jobs)

Our code returns: [].

The brackets without in between are an empty list.

We can specify some default values ​​by adding them between our brackets:

jobs = [’Software Engineer’,’Data Analyst’]

We have declared a list object with two initial values: "Software Engineer" and "Data Analyst".

Python Create List: list() Method

Another way to create an empty list with no values ​​in Python is to use the list () method. Here is an example of the list () method in action:

obs = list()
print(list)

Our code returns: [].

These first two approaches return the same response: an empty list. There are no standards for when it is best to use either of these approaches. In general, the empty square brackets ([]) method is used because it is more concise.

Python Declare List: List Multiplication

One method of initializing a multi-valued list is list multiplication. This way you can create a list with a certain number of predefined values.

Let’s say we create a program that asks us to name our 10 favorite books. We want to initialize an array that will store the books we input. We could do this with the following code:

favorite_books = [’’] * 10
print(favorite_books)

Our code returns:

[’’, ’’, ’’, ’’, ’’, ’’, ’’, ’’, ’’, ’’]

Our program has created a list containing 10 values.

We can use this syntax to initialize a list with any value. If we want our list to start with 10 values ​​that equal "select book" we can use the following code:

favorite_books = [’Choose a book.’] * 10
print(favorite_books)

When we run our code, we create a list of 10 values. Each value in the list equals Select Book. We print this list on the console:

[’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’]

Python Declare List: List Comprehension

In the previous section, we showed how to initialize a list using list multiplication. This approach is useful because it allows you to initialize a list of default values.

You can also initialize a list with default values ​​using the list comprehension method. Understanding Python lists refers to a technique that allows you to create lists using an existing iterable object. The iterable object can be a list or a range () statement or some other iterable type.

Comprehensive lists are a useful way to define an iterator-based list because it is elegant, simple, and widely accepted.

Let’s say we want to make a list of 10 values ​​that are equal to Pick a Book, as we did in the previous example. We could do this with list comprehension using the following code:

favorite_books = [’Choose a book.’ for i in range(10)]
print(favorite_books)

Our code returns:

[’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’, ’Choose a book.’]

In the example above, we used list comprehension to create a list. The list comprehension statement is the iterator for i in area (10). This iterator is used to build a list that repeats the Select Book value. ten times more.

For tuples and arrays

You can initialize tuples as well as lists.

Note that a tuple of one element requires ,.

One-element tuples require a comma in Python

t = (0,) * 5
print(t)
# (0, 0, 0, 0, 0)
source: list_initialize.py

For array type, you can pass the initialized list to the constructor.

import array

a = array.array(’i’, [0] * 5)
print(a)
# array(’i’, [0, 0, 0, 0, 0])

Which is faster to initialize lists in Python?

Python is a very flexible language where one task can be done in several ways, for example initializing lists can be done in different ways. However, there are subtle differences in these seemingly similar methods. Popular for its simplicity and readability, Python is equally known for its slowness compared to C++ or Java. The for loop is especially known to be slow, while methods such as map () and filter () are known to be faster because they are written in C. Knowing a better and faster way to initialize lists can give you little advantage in concurrent programming.

Here are some ways to initialize lists (create lists of 1000 size and initialize them with zeros) in Python.

Initialize list using the * operator

The * operator can be used as [object]*n where n is the no of elements in the array.

arr = [0]*1000

Lets look at the time taken by each of them. We will calculate the average time taken by each of these methods to initialize an array of 10000 elements over 500 times.

# import time module to calculate times
import time
  
# initialise lists to save the times
forLoopTime = []
whileLoopTime = []
listComprehensionTime = []
starOperatorTime = []
  
# repeat the process for 500 times
# and calculate average of times taken.
for k in range(500): 
  
    # start time
    start = time.time()
    # declare empty list
    a = []
    # run a for loop for 10000 times
    for i in range(10000):
        a.append(0)
    # stop time
    stop = time.time()
    forLoopTime.append(stop-start)
  
    # start time
    start = time.time()
    # declare an empty list
    a = []
    i = 0
    # run a for loop 10000 times
    while(i<10000):
        a.append(0)
        i+= 1
    stop = time.time()
    whileLoopTime.append(stop-start)
  
    start = time.time()
    # list comprehension to initialize list
    a = [0 for i in range(10000)] 
    stop = time.time()
    listComprehensionTime.append(stop-start)
  
  
    start = time.time()
    # using the * operator
    a = [0]*10000 
    stop = time.time()
    starOperatorTime.append(stop-start)
  
print("Average time taken by for loop: " + str(sum(forLoopTime)/100))
print("Average time taken by while loop: " + str(sum(whileLoopTime)/100))
print("Average time taken by list comprehensions: " + str(sum(listComprehensionTime)/100))
print("Average time taken by * operator: " + str(sum(starOperatorTime)/100))    

Output

Average time taken by for loop: 0.012432687282562256
Average time taken by while loop: 0.017907898426055908
Average time taken by list comprehensions: 0.0034629487991333007
Average time taken by * operator: 0.0001951146125793457

Conclusion

Initializing a list is an essential part of working with lists. This tutorial explained how to initialize empty lists with square brackets and the list () method. He also discussed how to use multiplication and list understanding techniques to build a list that contains a specific number of values.

Now you can start list initialization in Python like a pro!

Read our guide to learning Python for tips on how to learn more about the Python programming language.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically