Strange behavior

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Wed Aug 15 05:50:34 EDT 2012


Chris Angelico <rosuav at gmail.com> writes:

> Other people have explained the problem with your code. I'll take this
> example as a way of introducing you to one of Python's handy features
> - it's an idea borrowed from functional languages, and is extremely
> handy. It's called the "list comprehension", and can be looked up in
> the docs under that name,
>
> def testFunc(startingList):
>     xOnlyList = [strng for strng in startingList if strng[0] == 'x']
>     startingList = [strng for strng in startingList if strng[0] != 'x']
>     print(xOnlyList)
>     print(startingList)
>
> It's a compact notation for building a list from another list. (Note
> that I changed "str" to "strng" to avoid shadowing the built-in name
> "str", as others suggested.)

Fully agree with you: list comprehension is, imo, the most useful
program construct ever. Extremely useful.

But not when it makes the program traverse twice the same list, where
one traversal is enough.

-- Alain.



More information about the Python-list mailing list