[Tutor] who makes FOR loop quicker

Mark Lawrence breamoreboy at yahoo.co.uk
Wed Aug 5 15:27:23 CEST 2015


On 05/08/2015 08:53, John Doe wrote:
> To pass by reference or by copy of - that is the question from hamlet.
> ("hamlet" - a community of people smaller than a village python3.4-linux64)
>
> xlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> i = 0
> for x in xlist:
>      print(xlist)
>      print("\txlist[%d] = %d" % (i, x))
>      if x%2 == 0 :
>          xlist.remove(x)
>      print(xlist, "\n\n")
>      i = i + 1
>
> So, catch the output and help, PLEASE, me improve the answer:
> Does it appropriate ALWAYS reevaluate the terms of the list on each
> iteration?
> But if I want to pass a copy to FOR instead of a reference (as seen from
> an output) and reduce unreasonable reevaluation, what I must to do for
> that?

 From https://docs.python.org/3/tutorial/introduction.html#lists, but 
chopped around a little:-

<quote>
All slice operations return a new list containing the requested 
elements. This means that the following slice returns a new (shallow) 
copy of the list:

 >>> squares = [1, 4, 9, 16, 25]
 >>> squares[:]
[1, 4, 9, 16, 25]
</quote>

Hence:-

for x in xlist[:]:
   etc.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list