This code generates a list that consists of 9 ones.
>>> [1 for i in range(9)]
[1, 1, 1, 1, 1, 1, 1, 1, 1]
Is there a more faster way to do this?
This code generates a list that consists of 9 ones.
>>> [1 for i in range(9)]
[1, 1, 1, 1, 1, 1, 1, 1, 1]
Is there a more faster way to do this?
A faster (based on this post) and much shorter is using list multiplication:
>>> [1] * 9
[1, 1, 1, 1, 1, 1, 1, 1, 1]
You can just create an object that have an infinite - or a defined set of - whatever element you have, and this won't depend on the number of elements you want.
So, while it would not necessarily be "faster" for 9 ones than creating a list, it certainly would be faster for a couple hundred, and noticeably faster for 10 million or 1 billion ones:
class Ones:
def __init__(self, element=1, size=9):
self.element = element
self.size = size
def __getitem__(self, index):
return self.element
def __len__(self):
return self.size
Also, if you need to iterate only one over the repeated elements, instead of being able to get one at any arbitrary index, you can use itertools.repeat
:
import itertools
ones = itertools.repeat(1, size=9)