[Tutor] Query: lists

Peter Otten __peter__ at web.de
Tue Aug 14 18:16:15 EDT 2018


Alan Gauld via Tutor wrote:

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

For a simple solution you do need a and b: leave words unchanged, append 
words starting with "x" to a and words not starting with "x" to b.

Someone familiar with Python might do it with a sort key instead:

>>> sorted(['bbb', 'ccc', 'axx', 'xzz', 'xaa'],
... key=lambda s: not s.startswith("x"))
['xzz', 'xaa', 'bbb', 'ccc', 'axx']

If you want ['xaa', 'xzz', 'axx', 'bbb', 'ccc'] as the result
you can achieve that by sorting twice (Python's sorting is "stable") or by 
tweaking the key function.



More information about the Tutor mailing list