0

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?

Selcuk
  • 57,004
  • 12
  • 102
  • 110

2 Answers2

1

A faster (based on this post) and much shorter is using list multiplication:

>>> [1] * 9
[1, 1, 1, 1, 1, 1, 1, 1, 1]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

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)
jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • The question is specifically about lists though, not any iterator. – Selcuk Sep 03 '19 at 00:29
  • Indeed. But I guess this answer can be more useful if one needs repeated elements, even if one has the word "list" in mind. So, it might not be "correct" but it is certainly helpful for this case. – jsbueno Sep 03 '19 at 00:32
  • Agreed. I can't think of any use case that requires this approach though. I am assuming that one would want to be able to mutate elements after initializing the list. – Selcuk Sep 03 '19 at 00:39
  • 1
    well, that is why "itertools.repeat" is there - it is rare, but there are cases where one might want it. And all one needs is another place in code that expects a sequence, and you want to pass an identic-element sequence there, for this to have use. The approach is also valid for one wanting to mutate elements to keep a "sparse squence" were most elements are identical but the ones mutated - and associated dict, and 5 or 6 extra lines of code above would do that. – jsbueno Sep 03 '19 at 00:49