The most time/space efficient way to list all indices in an object

67 Views Asked by At

I am looking for 2 algorithms for creating a list of all indices in a string/list/etc.

I am not familiar with how range works. It is my understanding that using range creates an additional list in memory, and this is what I am trying to avoid here.

  • The most time efficient algorithm
  • The most space efficient algorithm

My code for optimal time:

string = 'sentence'
indices = []
for i in range(len(string)):
    indices.append(i)

My code for optimal space:

string = 'sentence'
indices = []
string_len = len(string)
i = 0
while i < string_len:
    indices.append(i)
    i += 1
2

There are 2 best solutions below

0
On BEST ANSWER

Optimal time and space:

string = 'sentence'
indices = range(len(string))        # Python 2
indices = list(range(len(string)))  # Python 3
0
On

I would think the most time-, space- and code-efficient way to do this would be this:

string = "sentence"
indices = range(len(string))

Also, for the record, if you replace range() with xrange() in your first suggestion, it is just as space-efficient as the second, since xrange() is lazy.