Python create list length

Initialize a list with given size and values in Python

This article explains how to initialize a list with any size (number of elements) and values in Python.

See the following article about the initialization of NumPy array ndarray .

Create an empty list

An empty list is created as follows. You can get the number of elements in a list with the built-in len() function.

l_empty = [] print(l_empty) # [] print(len(l_empty)) # 0 

You can add an element using the append() method and remove it using the remove() method.

l_empty.append(100) l_empty.append(200) print(l_empty) # [100, 200] l_empty.remove(100) print(l_empty) # [200] 

See the following articles for details on adding and removing elements from a list.

Initialize a list with any size and values

As mentioned above, in Python, you can easily add and remove elements from a list. Therefore, in most cases, it is not necessary to initialize the list in advance.

If you want to initialize a list with a specific size where all elements have the same value, you can use the * operator as shown below.

l = [0] * 10 print(l) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] print(len(l)) # 10 

A new list is created by repeating the elements of the original list for the specified number of times.

print([0, 1, 2] * 3) # [0, 1, 2, 0, 1, 2, 0, 1, 2] 

You can generate a list of sequential numbers with range() .

Notes on initializing a 2D list (list of lists)

Be cautious when initializing a list of lists.

Avoid using the following code:

l_2d_ng = [[0] * 4] * 3 print(l_2d_ng) # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 

With this code, updating one list will change all the lists.

l_2d_ng[0][0] = 5 print(l_2d_ng) # [[5, 0, 0, 0], [5, 0, 0, 0], [5, 0, 0, 0]] l_2d_ng[0].append(100) print(l_2d_ng) # [[5, 0, 0, 0, 100], [5, 0, 0, 0, 100], [5, 0, 0, 0, 100]] 

This issue occurs because all the inner lists reference the same object.

print(id(l_2d_ng[0]) == id(l_2d_ng[1]) == id(l_2d_ng[2])) # True 

Instead, you can use list comprehensions as demonstrated below.

l_2d_ok = [[0] * 4 for i in range(3)] print(l_2d_ok) # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 

Each inner list is treated as a separate object.

l_2d_ok[0][0] = 100 print(l_2d_ok) # [[100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] print(id(l_2d_ok[0]) == id(l_2d_ok[1]) == id(l_2d_ok[2])) # False 

Although range() is used in the above example, any iterable with the desired number of elements is acceptable.

l_2d_ok_2 = [[0] * 4 for i in [1] * 3] print(l_2d_ok_2) # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] l_2d_ok_2[0][0] = 100 print(l_2d_ok_2) # [[100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] print(id(l_2d_ok_2[0]) == id(l_2d_ok_2[1]) == id(l_2d_ok_2[2])) # False 

If you want to create a multidimensional list, you can use nested list comprehensions.

l_3d = [[[0] * 2 for i in range(3)] for j in range(4)] print(l_3d) # [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]] l_3d[0][0][0] = 100 print(l_3d) # [[[100, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]] 

Initialize a tuple and an array

You can also initialize tuples as well as lists.

Note that a single-element tuple requires a comma , to differentiate it from a regular value.

t = (0,) * 5 print(t) # (0, 0, 0, 0, 0) 

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

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

See the following article for the difference between list and array .

  • Difference between lists, arrays and numpy.ndarray in Python
  • Check if a list has duplicates in Python
  • GROUP BY in Python (itertools.groupby)
  • Get the number of items of a list in Python
  • Extract, replace, convert elements of a list in Python
  • Extract and replace elements that meet the conditions of a list of strings in Python
  • Convert numpy.ndarray and list to each other
  • Sort a list, string, tuple in Python (sort, sorted)
  • Convert pandas.DataFrame, Series and list to each other
  • Shuffle a list, string, tuple in Python (random.shuffle, sample)
  • Sort a list of dictionaries by the value of the specific key in Python
  • Deque with collections.deque in Python
  • Reverse a list, string, tuple in Python (reverse, reversed)
  • Add an item to a list in Python (append, extend, insert)
  • List comprehensions in Python

Источник

Create a List With a Specific Size in Python

Create a List With a Specific Size in Python

  1. Preallocate Storage for Lists
  2. Preallocate Storage for Other Sequential Data Structures

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.

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

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

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

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

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

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

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

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

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

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

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

Источник

Читайте также:  Python selenium click captcha
Оцените статью