Strange behavior

Chris Angelico rosuav at gmail.com
Tue Aug 14 17:55:58 EDT 2012


On Wed, Aug 15, 2012 at 1:38 AM,  <light1quark at gmail.com> wrote:
> def testFunc(startingList):
>         xOnlyList = [];
>         for str in startingList:
>                 if (str[0] == 'x'):
>                         print str;
>                         xOnlyList.append(str)
>                         startingList.remove(str) #this seems to be the problem
>         print xOnlyList;
>         print startingList
> testFunc(['xasd', 'xjkl', 'sefwr', 'dfsews'])

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

(Unrelated side point: Putting parentheses around the print statements
makes them compatible with Python 3, in which 'print' is a function.
Unless something's binding you to Python 2, consider working with the
current version - Python 2 won't get any more features added to it any
more.)

Python's an awesome language. You may have to get your head around a
few new concepts as you shift thinking from PHP's, but it's well worth
while.

Chris Angelico



More information about the Python-list mailing list