简体   繁体   中英

How do I manipulate a list with a function in Python (global scope)?

I have a list with integers and strings l = [1, 2, 'a', 'b'] and want to write a function that takes the list and manipulates it in a way that it just contains integers afterwards. The function output looks like what I want to have, but it doesn't change the "original" list.

def filter_list(l):
  temp =[]
  for item in l:
      if type(item) == int:
          temp.append(item)
  l = temp
  return l
Function output: [1, 2]
Variable explorer: [1,2,'a','b']

In contrast, the function

def manipulate(l):
    l.append("a")
    return l
Function output: [1, 2, 'a', 'b', 'a']
Variable explorer: [1, 2, 'a', 'b', 'a']

changes the "original" list.

  1. What's the difference between theses 2 function, ie why does the
    second one manipulate my "original" list, but the first one doesn't?
  2. How do I have to adjust function 1 in order to get the desired output?

Thanks!

In python, all objects are passed to functions by reference, meaning you can change the object passed to your function. That's why when you call the append method in your second example the list changes.

However, if you assign a different object to the argument that was passed ( l = temp ), then you change the reference itself and therefore can not make changes to the original object from the outer scope. That's not a problem in your case, though, because you return the new reference, as you should in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM