Fastest way to initialize a List in Python? (comparison of 3 options)

preview_player
Показать описание
Fastest way to initialize a List in Python? (comparison of 3 options)

Get my Free NumPy Handbook:

📓 ML Notebooks available on Patreon:

If you enjoyed this video, please subscribe to the channel:

~~~~~~~~~~~~~~~ CONNECT ~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~ SUPPORT ME ~~~~~~~~~~~~~~

#Python
Рекомендации по теме
Комментарии
Автор

Using [[0] * n] * n] creates a list of a list at the same point in memory, i.e. myList[0] is myList[1]

GN
Автор

I love how Python optimises some things, in ways that we might not have expected.

I really like your channel, I've only been programming Python for a year but you are helping to set important ideas in my head that were not obvious before.

Thank you.

calum.macleod
Автор

Mutables can create tricky situations, whether as multiplicative elements in lists, where it is effectively the same object in memory and repeated, or when used as default argument in a function, where if modified it will effectively change the default value of the next call to that function.

alexpaciniat
Автор

The optimization is (assuming that the underlying structure is an array list) probably due to the code knowing how big to make the list. The other ways probably default to 10 or something and double in size each time it gets too big

GyroCannon
Автор

+1 for the disclaimer to not use this technique in a nested list. Very useful for scenarios where latency is critical

pattmehta
Автор

#Fastest as it uses numpy, which is a low level language
import numpy as np
n = 5 # Replace 5 with your desired size
Listofzeros = np.zeros(n)
MyList = list(Listofzeros)
print(MyList)

shivanshmathur
Автор

Sir, Loeber!! Thank you for the content on your YT channel.

pzkpfw
Автор

I've recognized it when creating a 2d list:
board1 = [[0]*3]*3
# would be different from
board2 = [[0 for j in range(3)] for i in range(3)]

# let's take a closer look
# when I want to update the cell data of the board[row][column]

>>> board1[0][0] = 1
>>> board1
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
>>> board2[0][0] = 1
>>> board2
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

# it's dangerous. Be careful with this python behavior:)
# Using list-comprehension is the correct way.

ytusr-korg
Автор

You cant multiply nested list.
You have to use loop for creating it

bekhzodravshanov
Автор

Thank you..what IDE are you using please

amrosamier
Автор

Why do you write the "_" in "for _ in list"? You usually use something like "for element in list", don't you?

MrJonas