I have an array that I have to add a new value to array value. I am new to arrays. how do I loop thru the array and add to the value in the existing array.
A:
First of all i think arrays can not be nested (somehow i get a feeling that's what you are saying in your question).
As for adding value to a array it's simple:
>>> from array import array
>>> x = array('l', [1, 12, 80, 5, 3])
>>> x.append(444)
>>> x
array('l', [1, 12, 80, 5, 3, 444])
>>>
>>> for i in range(0, len(x)):
... x[i] = 1
...
>>> x
array('l', [1, 1, 1, 1, 1, 1, 1])
>>> x = array('l', [1,2,3,4])
>>> x[2] = 33
>>> x
array('l', [1, 2, 33, 4])
>>>
You could also use insert().
rebus
2010-05-07 13:56:54
most people would assume that the OP just doesn't know the difference between lists and arrays, and actually works with lists.
SilentGhost
2010-05-07 14:17:42
Yes i assumed that too, and gave an example of a list and dict first, but then ran over python docs and updated myself on arrays, so while he is mentioning arrays i question i wrote this just for a reference.
rebus
2010-05-07 14:21:26
Thank you. It looks fairly close to what I am after.
foo wei tau
2010-05-07 14:42:40
No need to thank, but do consider elaborating your question and give an examples of how your array looks like and how you want it to look after you do things to it, you'll get much more help that way.
rebus
2010-05-07 15:21:49
A:
a = [2, 3, 4]
for i in range(0, len(a)):
a[i] += 3
print a #prints [5, 6, 7]
Amarghosh
2010-05-07 14:01:00
+3
A:
>>> print [x+2 for x in [1,2,3]]
[3, 4, 5]
>>>
Learn about Python lists and list comprehensions
N 1.1
2010-05-07 14:02:11
A:
If you are working with arrays and need to do some math I would definitely recommend you numpy. Numpy was made for this purpose. Another hint (to all what I know): try to avoid loops where you can.
Reason: The code reads more clearly and is very likely to be faster. Here an example what numpy can do:
In [1]: import numpy as np
In [2]: x = np.array([4,5,6,7,8])
In [3]: x+3
Out[3]: array([ 7, 8, 9, 10, 11])
In [4]: x**2
Out[4]: array([16, 25, 36, 49, 64])
In [5]: x>=6
Out[5]: array([False, False, True, True, True], dtype=bool)
For further reading I recommend the numpy tutorial.
basweber
2010-05-08 14:58:10