0

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)
DT1
  • 126
  • 4

2 Answers2

3
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.

Rohit-Pandey
  • 2,039
  • 17
  • 24
1

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.

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
  • btw, it is called `list` in Python and not `array`. – Krishna Chaurasia Mar 01 '21 at 06:05
  • So, the loop extends the list and fill it at the same time, correct? In python, there is no cost in re-dimensioning a list? – DT1 Mar 01 '21 at 06:08
  • yes, no extra cost with re-demensioning with list comprehension. you can read more about how [list comprehension works](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) in detail. – Krishna Chaurasia Mar 01 '21 at 06:11