Strange behavior

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Tue Aug 14 11:59:42 EDT 2012


light1quark at gmail.com writes:

> However if you run the code you will notice only one of the strings
> beginning with 'x' is removed from the startingList.

>
> 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'])
>
> #Thanks for your help!

Try with ['xasd', 'sefwr', 'xjkl', 'dfsews'] and you'll understand what
happens. Also, have a look at:

http://docs.python.org/reference/compound_stmts.html#the-for-statement

You can't modify the list you're iterating on, better use another list
to collect the result.

-- Alain.

P/S: str is a builtin, you'd better avoid assigning to it.



More information about the Python-list mailing list