1

Is this the correct way to declare and iterate through an array in Python, where each element is multiplied by a constant value?

timeArray = array([0]*1000)

for x in timeArray:
    timeArray[x] = x * deltaTime
    print(timeArray)
agf
  • 171,228
  • 44
  • 289
  • 238
kachilous
  • 2,499
  • 11
  • 42
  • 56
  • 5
    Are you sure you want an [`array`](http://docs.python.org/library/array.html) and not the data structure that's essentially an array but is called list in Python? –  Jun 20 '11 at 16:18
  • I read somewhere that lists aren't good for large data structures. – kachilous Jun 20 '11 at 16:19
  • 4
    If you're having *millions* of items which are equivalent to basic C data types (`int`s, `float`s, `char`, etc - see the docs), it's sometimes a useful optimization to use `array`. If that's not the case, or the code doesn't even run correctly yet (remember: "make it run, make it correct, make it fast" - optimizing is done *last*), you shouldn't even think of such optimizations. Complexity-wise, lists are just as good. –  Jun 20 '11 at 16:21

3 Answers3

4
timeArray = [i*deltaTime for i in range(1000)]

will construct a list with the contents that you want. Indexing into a list takes O(1) time, the same as for an array. Python lists are very fast, they're actually implemented as arrays.

Are you sure you want to print the contents of the array/list while it's being constructed?

(Aside: If you want faster arrays because you're doing number crunching, then a Numpy array might be a better choice:

timeArray = numpy.arange(1000)
timeArray *= deltaTime

)

Community
  • 1
  • 1
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0

This is probably less confusing, and does what you want.

timeArray = [0 for i in range(1000)]

for x in timeArray:
    timeArray[x] *= deltaTime
    print(timeArray)
Andrea
  • 19,134
  • 4
  • 43
  • 65
  • 3
    Or just `timeArray = [i*deltaTime for i in range(1000)]` – Fred Foo Jun 20 '11 at 16:21
  • -1 This is incorrect, and rather verbose at that. It takes four lines to repeatedly set `timeArray[0] = 0`, and also prints the same 1000-element array 1000 times. @larsmans's version is great, please post it as an answer. –  Jun 20 '11 at 16:24
0

It looks like what you really need are numpy arrays. The built-in array behaves more like lists.

#!/usr/bin/python

from array import array

timeArray = array("f", [1]*1000)

deltaTime = 2

for i, x in enumerate(timeArray):
    timeArray[i] = timeArray[i] * deltaTime

print(timeArray)

# but numpy arrays behave more "naturally".

from numpy import array
timeArray = array([1]*1000, dtype="f")
print (timeArray * 2)

A numpy array will multiply all elements of the array by a scalar value. Besides, I'm not sure that your original array code actually works. Also, numpy arrays are much faster.

Keith
  • 42,110
  • 11
  • 57
  • 76