[Tutor] Query: lists
Deepti K
kdeepti2013 at gmail.com
Tue Aug 14 18:36:35 EDT 2018
Thanks all. This is very helpful. I am new to Python :)
Sent from my iPhone
> On 15 Aug 2018, at 8:16 am, Peter Otten <__peter__ at web.de> wrote:
>
> 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.
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list