I was writing a code for the adjacency matrix for a graph and found this question:
Best and/or fastest way to create lists in python
So, I simply wrote this to initialize my adjacency matrix as it seemed the fastest way to initialize a list so far.
import time
t1 = time.time()
matrix = [[0]*5000]*5000
t2 = time.time()
t2-t1
0.0
But after doing some operations, I realized each time I changed/appended an element the effect is applied to all the sub-lists, which means each list is just a reference and this will not work for a real scenario even though it's fast.
I can't use numpy, as algorithmic sites don't allow external modules/libraries. I think numpy would've been the ideal solution for the general scenario.
Now, obviously most other 2d/multi-dim list initialization answers suggest list comprehension,
import time
t1 = time.time()
matrix = [[0 for i in range(5000)] for j in range(5000)]
t2 = time.time()
print(t2-t1)
0.7021145820617676
But, it seems slow (compared to other languages) considering the strict time limit for solving a graph problem in an algorithmic site.
Is there a faster way to initialize a 2d/3d list in python?
Let me know if there is a duplicate, so far I didn't find anything which shows some time comparison between methods for multi-dimensional list initialization.
Dict[Node, [List[Node]]]) fine as well?