Lists and arrays

Dave Angel davea at davea.name
Mon Apr 22 14:34:42 EDT 2013


On 04/22/2013 02:13 PM, Ana Dionísio wrote:
> Hello!
>
> I need your help!
>
> I have an array

I think you mean you have a numpy array, which is very different than a 
python array.array


> and I need pick some data from that array and put it in a list, for example:
>
> array= [a,b,c,1,2,3]

That's a list.

>
> list=array[0]+ array[3]+ array[4]

Nothing wrong with that, other than that you just hid the name of the 
list type, making it tricky to later convert things to lists.

>
> list: [a,1,2]

You'll never get that.  When you assign an object to a list, the object 
itself is referenced in that list, not the name that it happened to have 
before.  So if a was an object of type float and value 41.5, then you 
presumably want:
    mylist: [41.5, 1, 2]


>
> When I do it like this: list=array[0]+ array[3]+ array[4] I get an error:
>
> "TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'numpy.ndarray'"
>

Apparently you did not use the line
     array= [a,b,c,1,2,3]

as you said above, but some other assignment, perhaps using a numpy 
method or six.  Worse, apparently the elements of that collection aren't 
simple numbers but some kind of numpy thingies as well.

If you show what you actually did, probably someone here can help, 
though the more numpy you use, the less likely that it'll be me.


If you really had a list, you wouldn't have gotten an error, but neither 
would you have gotten anything like you're asking.  array[3] + array[4] 
== 1+2 == 3.  If you're trying to make a list using + from a subscripted 
list, you'd have to enclose each integer in square brackets.

mylist = [array[0]] + [array[3]] + [array[4]]

Alternatively, you could just do

mylist = [ array[0], array[3], array[4] ]

-- 
DaveA



More information about the Python-list mailing list