Перейти к содержимому

Как создать список определенной длины в питоне

  • автор:

Как в питоне объявить список фиксированной длины, но не заполнять его?

Вызове ошибку MemoryError , потому, что список в добавок к объявлению заполняется числами от 0 до 999999999.

MaxU - stand with Ukraine's user avatar

Список фиксированной длины — это скорее всего МАССИВ. Тогда так:

только он будет заполнен «остаточным мусором», а не «Ничем». Ничем вам показали в другом ответе )
Реализация массива в numpy намного более экономна по расходованию памяти, чем стандартный список, но не позволяет хранить объекты разных типов и добавлять или удалять элементы массива.
Кстати — если тип не указывать, то будет массив float

Список в Питоне содержит ссылки на объекты. Нельзя создать список, заданного размера, не заполнив его. Даже если все ссылки указывают на None:

необходимо место под сами ссылки и рано или поздно вы получите MemoryError (мне не известны реализации Питона, где списки лениво создаются). См. Размер списка в Python и объём оперативной памяти

В качестве альтернативы, вы можете пустой список создать:

и добавлять к нему элементы к нему по мере необходимости ( L.append(<>) ). Это не спасёт от MemoryError при достаточно большом количестве элементов.

Если вы хотите создать массив чисел, то для экономии памяти можно использовать array модуль, который может более компактное представление иметь. К примеру, что создать массив с миллиардом нулей:

Это меньше памяти чем обычный список может занимать, но от MemoryError при достаточно больших размерах это не спасёт (также как и numpy.empty(10**9) ). Reserve memory for list in Python?

Чтобы память не требовать, можно использовать ленивые последовательности, к примеру, в Питоне 3:

Нужные элементы на лету могут создаваться. Большие размеры, такие как range(10**21) , не приводят к MemoryError в этом случае. Можно также свои классы создавать, к примеру, размер GmtimeOverflowTable практически не ограничен.

Create a List With a Specific Size in Python

Create a List With a Specific Size in Python

Preallocating storage for lists or arrays is a typical pattern among programmers
when they know the number of elements ahead of time.

Unlike C++ and Java, in Python, you have to initialize all of your pre-allocated storage with some values. Usually, developers use false values for that purpose, such as None , » , False , and 0 .

Python offers several ways to create a list of a fixed size, each with
different performance characteristics.

To compare performances of different approaches, we will use Python’s standard
module timeit .
It provides a handy way to measure run times of small chunks of Python code.

Preallocate Storage for Lists

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

A million iterations (default value of iterations in timeit ) take approximately
117 ms.

Another approach is to use the range built-in function with a list comprehension.

It’s almost six times slower and takes 612 ms second per million iterations.

The third approach is to use a simple for loop together with the list.append() .

Using loops is the slowest method and takes 842 ms to complete a million iterations.

Preallocate Storage for Other Sequential Data Structures

Since you’re preallocating storage for a sequential data structure, it may make a lot of sense to use the array built-in data structure instead of a list.

As we see below, this approach is second fastest after [None] * 10 .

Let’s compare the above pure Python approaches to the NumPy Python package for scientific computing.

The NumPy way takes 589 ms per million iterations.

However, the NumPy way will be much faster for more massive lists.

The conclusion is that it’s best to stick to [None] * 10 for small lists, but switch
to NumPy’s empty() when dealing with more massive sequential data.

Создание списка в Python из N элементов

Python предоставляет удобные и мощные инструменты для работы со списками. Ниже приведены примеры того, как можно создать список из N элементов в Python.

1. Использование цикла for

В этом примере мы создали пустой список, затем добавили в него элементы в цикле с помощью метода append().

2. Использование списковых включений

Списковые включения — это мощный инструмент Python, который позволяет создавать и заполнять списки в одной короткой строке кода.

3. Использование функции list()

Функция list() преобразует итерируемый объект (в данном случае, результат выполнения функции range()) в список.

4. Использование оператора *

В этом примере мы создаем список, состоящий из одного элемента (ноль), а затем умножаем его на N, чтобы получить список из N нулей.

How to create an array of numbers 1 to n in python

An array is a collection of items of the same type stored at contiguous memory locations. To access the elements, you only need to know the memory address of the first item of an array which is also known as the base address. You can access all other items or traverse in an array by simply adding an offset to this base address. Python lists can also be treated as arrays but the lists can store multiple data items of different datatypes. This article is about how to create an array of numbers 1 to N in Python. If you want to learn more about Python Programming, visit Python Programming Tutorials.

Please enable JavaScript

To create an array of numbers from 1 to N in python, range() Function can be used. Other methods include creation of an array using user-defined function, numpy.arrange() function and python array module. All these methods can be used for creating an array of numbers 1 to N in Python.

In the first three methods, we’ll see how lists can be treated as arrays. Python has a module called array which is used to work only with specific data values. The last method discusses how to create an array using this module. Let’s discuss all these methods in detail.

What We’ll Cover

Creating an array using the Range() Function

As discussed previously, python lists can be treated as arrays. To create an array of a certain range, we can use the range() function as it specifies the range of the list and then typecast the range() by using the list command as shown in the code below. We can set the range of the list from 1 to N and N should be any integer number.

Output:

Creating an array by a user-Defined Function

Another way is to create a function and pass the length of an array as a parameter to this function. In the example below, we have created a function by the name of List-Function. The function takes parameter ‘n’ which represents the length of the array. In this function, a for loop is used which treats n as the last index of the array and appends the number in the List_array starting from 0 up to the maximum length ‘n’ as shown below.

Output:

Creating an array using NumPy.ARRANGE() Function

The NumPy library provides an arrange() function which takes two parameters as integers and generates the numbers starting from the first parameter up to the last parameter. Typecast the arange() function using the list command and an array is created.

Output:

numpy.arange() is used to create an array of large sizes.

Create an array using the Python Module Array

An array module of Python is used to create an array consisting of elements or items of same datatypes. The array module takes two arguments as input. The first one is the datatype of an array such as ‘i’ for integer. All other datatypes are given in this link. The second argument consists of the elements or items of an array.

Output:

In the example above, we have created two arrays arr1 and arr2 of integers and floating numbers. The function display here is used to print the contents of an array created. It takes two arguments: an array ‘n’ and the size of array ‘s’ created.

There are different operations that can be carried out on arrays such as insertion, deletion, sorting arrays into ascending and descending order, etc. Try them on your own. If you have any queries regarding this topic or any other topic related to Python programming language, let us know in the comments or contact us.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *