On 18/01/15 00:49, Colin Ross wrote:

a = [0,1,2,3,4,5,6,7,8,9,10]
b = [10,20,30,40,50,60,70,80,90,100,110]

for a in range(len(a)):
    if a > 5:
       print a

You have named your iteration cvariable the same as the list you are iterating over. Don't ever do this!

In effect you have made your list invisible.
Python just sees:

for a in range(11):

and a becomes each integer in turn.
At the end of the loop a is the number 10.

a_1 = np.array(a)
print a_1

So now you try to create an array using just the number 10.

The desired result is: [6,7,8,9,10}

You could just rename the iteration variable:

for x in range(len(a)):
    if x > 5:
       print x

You would be better using a list comprehension:

a_1 = [x for x in range(len(a)) if x > 5]
print a_1

or to create the array directly:

a_1 = array(x for x in range(len(a)) if x > 5)

should work.

BTW I assume you will eventually want the contents
of the original list rather than the indexes?
If so it woyuld look like:

a_1 = array(a[x] for x in range(len(a)) if a[x] > 5)

or, working on the list directly, and more generally:

a_1 = array(item for item in a if test(item) )

where test() is any filter function you care you write.



HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to