DT1
DT1

Reputation: 136

How to quickly iterate through an array in python

I'm learning python, and I found myself on some bottleneck I don't understand.

The part where I wrote on the file is quick, but the iteration or maybe the creation of the list is really slow.

This snippet runs in something less than a second and it's not possible.

What I'm doing wrong? Thanks

import sys
import time

t0=time.time() 
arr=list(range(1,10000))
for i in arr:
    arr[arr.index(i)]= 'dsaijhjsdha' + str(i) + '\n'

open("bla.txt", "wb").write(bytearray(''.join(arr),'utf-8'))
d=time.time()-t0
print ("duration: %.2f s." % d)

Upvotes: 0

Views: 1769

Answers (2)

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

import sys
import time

t0=time.time() 
arr=list(range(1,10000))
for i in arr:
    arr[i-1]= 'dsaijhjsdha' + str(i) + '\n'

open("bla.txt", "wb").write(bytearray(''.join(arr),'utf-8'))
d=time.time()-t0
print ("duration: %.2f s." % d)

Have a look at the above solution. This will achieve the same output as you want.

Output: duration: 0.02 s.

Upvotes: 3

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9580

You can do all of this in one line with list comprehension as:

Use this:

arr = ['dsaijhjsdha' + str(i) + '\n' for i in range(1, 10000)]    
print(arr)

instead of:

arr=list(range(1,10000))
for i in arr:
    arr[arr.index(i)]= 'dsaijhjsdha' + str(i) + '\n'

Using arr.index(i) is unnecessarily adding to the cost of computation.

Upvotes: 1

Related Questions