Strange behavior

light1quark at gmail.com light1quark at gmail.com
Tue Aug 14 11:38:15 EDT 2012


Hi, I am migrating from PHP to Python and I am slightly confused.

I am making a function that takes a startingList, finds all the strings in the list that begin with 'x', removes those strings and puts them into a xOnlyList.

However if you run the code you will notice only one of the strings beginning with 'x' is removed from the startingList.
If I comment out 'startingList.remove(str);' the code runs with both strings beginning with 'x' being put in the xOnlyList.
Using the print statement I noticed that the second string that begins with 'x' isn't even identified by the function. Why does this happen?

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!



More information about the Python-list mailing list