[Tutor] Query: lists

Alan Gauld alan.gauld at yahoo.co.uk
Tue Aug 14 17:35:14 EDT 2018


On 14/08/18 09:11, Deepti K wrote:
>  when I pass ['bbb', 'ccc', 'axx', 'xzz', 'xaa'] as words to the below
> function, it picks up only 'xzz' and not 'xaa'

Correct because....

> def front_x(words):
>   # +++your code here+++
>   a = []
>   b = []
>   for z in words:
>     if z.startswith('x'):
>       words.remove(z)

You just changed the thing you are iterating over.
By removing an elem,ent the list got shorter so the
internal counter inside the for loop now points at
the next item - ie it skipped one.

As a general rule never modify the thing you are
iterating over with a for loop - use a copy or
change to a while loop instead.


>       b.append(z)
>       print 'z is', z
>   print 'original', sorted(words)

But it's not the original because you've removed
some items.

>   print 'new', sorted(b)
>   print sorted(b) + sorted(words)

But this should be the same as the original
(albeit almost sorted).

PS. Since you only modify 'b' and 'words' you
don't really need 'a'

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




More information about the Tutor mailing list