Strange behavior
Terry Reedy
tjreedy at udel.edu
Tue Aug 14 15:05:43 EDT 2012
On 8/14/2012 11:59 AM, Alain Ketterlin wrote:
> 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,
Except he obviously did ;-).
(Modifying set or dict raises SomeError.)
Indeed, people routine *replace* items while iterating.
def squarelist(lis):
for i, n in enumerate(lis):
lis[i] = n*n
return lis
print(squarelist([0,1,2,3,4,5]))
# [0, 1, 4, 9, 16, 25]
Removals can be handled by iterating in reverse. This works even with
duplicates because if the item removed is not the one tested, the one
tested gets retested.
def removeodd(lis):
for n in reversed(lis):
if n % 2:
lis.remove(n)
print(n, lis)
ll = [0,1, 5, 5, 4, 5]
removeodd(ll)
>>>
5 [0, 1, 5, 4, 5]
5 [0, 1, 4, 5]
5 [0, 1, 4]
4 [0, 1, 4]
1 [0, 4]
0 [0, 4]
> better use another list to collect the result.
If there are very many removals, a new list will be faster, even if one
needs to copy the new list back into the original, as k removals from
len n list is O(k*n) versus O(n) for new list and copy.
> P/S: str is a builtin, you'd better avoid assigning to it.
Agreed. People have actually posted code doing something like
...
list = [1,2,3]
...
z = list(x)
...
and wondered and asked why it does not work.
--
Terry Jan Reedy
More information about the Python-list
mailing list