JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

How to create a list of a specific size in Python

Author:JIYIK Last Updated:2025/05/09 Views:

Preallocating storage for a list or array is a common practice among programmers when they know the number of elements in advance.

Unlike C++and Java, in Python you must initialize all preallocated storage with some value. Typically, developers use dummy values ​​for this purpose, such as None, '', Falseand 0.

Python provides several ways to create fixed-size lists, each with different performance characteristics.

To compare the performance of different approaches, we will use Python's standard module timeit, which provides a convenient way to measure the running time of a small piece of Python code.


Preallocate storage for lists

The first, and fastest, method is to use *the operator, which repeats a list a specified number of times.

>>> [None] * 10
[None, None, None, None, None, None, None, None, None, None]

One million iterations ( timeitthe default iteration value) takes about 117 milliseconds.

>>> timeit("[None] * 10")
0.11655918900214601

Another approach is to rangeuse built-in functions with list comprehensions.

>>> [None for _ in range(10)]
[None, None, None, None, None, None, None, None, None, None]

It is nearly six times slower, taking 612 milliseconds per million iterations.

>>> timeit("[None for _ in range(10)]")
0.6115895550028654

The third method is to use list.append()with fora loop.

>>> a = []
>>> for _ in range(10):
...   a.append(None)
...
>>> a
[None, None, None, None, None, None, None, None, None, None]

Using a loop is the slowest method, requiring 842 milliseconds to complete one million iterations.

>>> timeit("for _ in range(10): a.append(None)", setup="a=[]")
0.8420009529945673

Preallocating storage for other sequential data structures

Since you're pre-allocating storage for a sequential data structure, it arrayprobably makes more sense to use a built-in data structure instead of a list.

>>> from array import array
>>> array('i',(0,)*10)
array('i', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

As shown below, this method is second only to [None] * 10.

>>> timeit("array('i',(0,)*10)", setup="from array import array")
0.4557597979946877

Let's NumPycompare the above pure Python approach with Python libraries for scientific computing.

>>> from numpy import empty
>>> empty(10)
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

The NumPy method takes 589 milliseconds per million iterations.

>>> timeit("empty(10)", setup="from numpy import empty")
0.5890094790011062

However, for larger lists, the NumPy method will be faster.

>>> timeit("[None]*10000")
16.059584009999526
>>> timeit("empty(10000)", setup="from numpy import empty")
1.1065983309963485

The conclusion is that for small lists it is best to use [None] * 10, but switch to NumPy when dealing with larger amounts of sequential data empty().

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Finding a string in a list in Python

Publish Date:2025/05/09 Views:75 Category:Python

This tutorial shows you how to find elements from a Python list that have a specific substring in them. We will use the following list and extract ack the strings that have in it. my_list = [ "Jack" , "Mack" , "Jay" , "Mark" ] for Find elem

Getting list shape in Python

Publish Date:2025/05/09 Views:139 Category:Python

In Python, knowing the shape of a list is very important for working with data structures, especially when it comes to multidimensional or nested lists. This article explores various ways to determine the shape of a list in Python, from sim

Adding multiple elements to a list in Python

Publish Date:2025/05/09 Views:180 Category:Python

List is a mutable data structure in Python. It can contain values ​​of different types. This article will discuss some methods to append single or multiple elements to a Python list. append() Append a single element in a Python list usi

Get the index of the maximum and minimum values in a list in Python

Publish Date:2025/05/09 Views:117 Category:Python

In this tutorial, we will discuss methods to get the index of the maximum and minimum value of a list in Python. max() Get the index of the maximum value in a list using and list.index() functions in Python max() The function gives the maxi

List of numbers from 1 to N in Python

Publish Date:2025/05/09 Views:116 Category:Python

This tutorial will discuss how to create a list of numbers from 1 to some specified number. Create a user-defined function to create a list of numbers from 1 to N This method will take the desired number from the user and for iterate until

Convert List to Pandas DataFrame in Python

Publish Date:2025/05/09 Views:133 Category:Python

This article will show you how to convert items in a list into a Pandas DataFrame. Convert List to Pandas DataFrame in Python DataFrame, in general, is a two-dimensional labeled data structure. Pandas is an open source Python package that i

Sorting a list by another list in Python

Publish Date:2025/05/09 Views:148 Category:Python

Normally, when we sort a list, we do it in ascending or descending order. However, we can sort a list based on the order of another list in Python. We will learn how to sort a given list based on the values ​​in another list in this art

Normalizing a list of numbers in Python

Publish Date:2025/05/09 Views:134 Category:Python

Normalization means converting the given data to another scale. We rescale the data so that it is between two values. Most of the time, the data is rescaled between 0 and 1. We rescale data for different purposes. For example, machine learn

How to Find the Maximum Value in a List in Python

Publish Date:2025/05/09 Views:99 Category:Python

This tutorial will demonstrate how to find the maximum value in a list in Python. This tutorial will cover a number of scenarios and data types, from simple lists of integers to more complex structures like arrays within arrays. for Finding

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial