2

Possible Duplicate:
What is the difference between list and list[:] in python?

I am quite new in python so I bumped into a situation where I was unable to find a response for the following question.

What does this means in python?

l[:] = process_list(l)

l is type list

Basically I have a global declared list that I want to modify it(override the old values with the new ones) based on the response of the process_list method. When I try like this:

l = process_list(l)

I get this: Unresolved reference 'l'

Can you please explain what is the difference and if the first approach that I am using currently is a good one?

Community
  • 1
  • 1
andreea.sandu
  • 212
  • 1
  • 9

2 Answers2

4

In a function, an assignment to a name that could be a local variable creates a local variable by that name, even if it shadows a global:

a = None
def foo():
    a = 5  # local 'a' shadows global 'a'

Slice assignment is modification, not assignment, so the name continues to refer to the global:

a = [1, 2, 3]
def foo():
    a[:] = [5]  # modifies global 'a'

The Unresolved reference happens because by creating a local variable shadowing the global, the global can no longer be seen. Another way to do what you want could be to use global:

a = None
def foo():
    global a
    a = 5  # rebinds global 'a'
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Thank you so much for this clear and simple explanation! – andreea.sandu Dec 10 '12 at 20:08
  • Can you help me with something? I am trying to assign to that list(globally declared) a dictionary. Until a point in the program I used it as a list but now I am want it as a dictionary. What should be the best way to do it? Thank you! – andreea.sandu Dec 10 '12 at 20:14
  • 1
    @andreea.sandu use `global a`, then you can write `a = {}`. – ecatmur Dec 11 '12 at 08:27
2

list[:] = whatever will change the contents of the existing list

(as opposed to replacing it with list = whatever) ... by the way list is a terrible variable name ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179