Advertisement
gruntfutuk

python pass by what

Mar 28th, 2017
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. # Confused by way variables are passed in Python
  2. # I know pass-by-value and pass-by-reference do not apply
  3. # but explanations I have found are not making sense
  4. # to me.
  5.  
  6. # I have created a very simple script to help me illustrate
  7. # what I am confused by
  8.  
  9. # I create a list called dinner with a couple of menu items
  10. # pass that to a function, that adds two items
  11. # then attempts to completely replace the menu
  12. # the replaced menu is returned
  13.  
  14. # What happens?
  15. # The orignal list has two items added by the function
  16. # but the menu (list contents) are NOT replaced
  17. # by the function alternative, but that alternative
  18. # is returned by the function
  19.  
  20. # So, it seems that I can change the object referenced by the
  21. # passed variable, but if I assign new values to the local
  22. # variable, then I effective create a reference to a new object
  23.  
  24. def meal(plate):
  25.     plate.append('eggs')
  26.     plate.append('beans')
  27.     plate = ['tofu', 'soya eggs', 'nuts']
  28.     return plate
  29.  
  30. dinner = ['bacon', 'sausage']
  31. veggie = meal(dinner)
  32. print("Dinner: {}.".format(dinner))
  33. print("Veggie: {}.".format(veggie))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement