Drowning in a teacup?
Steven D'Aprano
steve at pearwood.info
Fri Apr 1 18:46:10 EDT 2016
On Sat, 2 Apr 2016 07:27 am, Fillmore wrote:
>
> notorious pass by reference vs pass by value biting me in the backside
> here. Proceeding in order.
Python is NEITHER pass by reference nor pass by value.
Please read this:
http://import-that.dreamwidth.org/1130.html
before asking any additional questions.
> def bringOrderStringToFront(mylist, key):
>
> for i in range(len(mylist)):
> if(mylist[i].startswith(key)):
> mylist = [mylist[i]] + mylist[:i] + mylist[i+1:]
[mylist[i]] + mylist[:i] + mylist[i+1:]
creates a new list. It doesn't modify the existing list.
mylist = ...
performs an assignment to the LOCAL VARIABLE mylist, setting it to the new
list just created. The original list is unchanged.
Trick: you can use slicing to write to the original list:
mylist[:] = [mylist[i]] + mylist[:i] + mylist[i+1:]
Or you can modify the list directly in place:
for i in range(len(mylist)):
if mylist[i].startswith(key):
x = mylist[i]
del mylist[i]
mylist.insert(0, x)
which is better written as:
for i, x in enumerate(mylist):
if x.startswith(key):
del mylist[i]
mylist.insert(0, x)
or if you prefer:
for i, x in enumerate(mylist):
if x.startswith(key):
mylist[:] = [x] + mylist[:i] + mylist[i+1:]
--
Steven
More information about the Python-list
mailing list