Drowning in a teacup?

Rob Gaddi rgaddi at highlandtechnology.invalid
Fri Apr 1 16:39:59 EDT 2016


Fillmore wrote:

>
> notorious pass by reference vs pass by value biting me in the backside 
> here. Proceeding in order.
>
> I need to scan a list of strings. If one of the elements matches the 
> beginning of a search keyword, that element needs to snap to the front 
> of the list.
> I achieved that this way:
>
>
>     for i in range(len(mylist)):
>          if(mylist[i].startswith(key)):
>              mylist = [mylist[i]] + mylist[:i] + mylist[i+1:]
>
> Since I need this code in multiple places, I placed it inside a function
>
> def bringOrderStringToFront(mylist, key):
>
>      for i in range(len(mylist)):
>          if(mylist[i].startswith(key)):
>              mylist = [mylist[i]] + mylist[:i] + mylist[i+1:]
>
> and called it this way:
>
>   if orderstring:
>       bringOrderStringToFront(Tokens, orderstring)
>
> right?
> Nope, wrong! contrary to what I thought I had understood about how 
> parameters are passed in Python, the function is acting on a copy(!) and 
> my original list is unchanged.
>

Nope, that's not your problem.  Your problem is the line:

>              mylist = [mylist[i]] + mylist[:i] + mylist[i+1:]

Which should be read as: "Take mylist[i], all of mylist before i,
and all of mylist after i and create a new list from it. Store that
new list in a variable called mylist, overwriting the previous value."

If instead you were using the .insert and .remove methods, you'd be
manipulating the existing list instead.  But you don't want to do that,
because those methods are O(N) on the list length; manipulating the
middle of lists is slow.

That said, you've got some logic problems too; which come from the fact
that your iteration is shooting at a moving target.

How about:
  newlist = (
    [x for x in mylist if x.startswith(key)] +
    [x for x in mylist if not x.startswith(key)]
  )
  return newlist

Or if you really insist on mutating the original list (which seems less
clean to me, but you do you), then:
  newlist = blahblahblah
  mylist[:] = newlist

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list