Python Forum
difference between forms of input a list to function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
difference between forms of input a list to function
#7
You can use module 'memory_graph':

https://pypi.org/project/memory-graph

to see the call stack. Here stack frame "0: <module>" holds all the global variables and stack frame "1: f" holds the local variables of the f() function.

import memory_graph # see install instructions at link above
id(b)
def f(a):
    a[0]=3
    print("a: ",a, "id(a): ",id(a))
    memory_graph.show( memory_graph.get_call_stack() ) # draw call stack
 
f(b)
print("b , id(b)",b,id(b))
[Image: g2.png]

In the first program we see that after calling the f() function variable local variable 'a' shares its data with global variable 'b' of the calling frame. Therefore if 'a' is changed 'b' is also changed.

Now the second program:

import memory_graph
id(b)
def f(a):
    a[0]=3
    print("a: ",a, "id(a): ",id(a))
    memory_graph.show( memory_graph.get_call_stack() ) # draw call stack
    
f(b[:])
print("b , id(b)",b,id(b))
[Image: g1.png]

Here f() is called with 'b[:]' (list slicing), so a copy of its data is send to f(). Therefore the local variable 'a' does not share any data with global variable 'b' of the calling frame and when 'a' is changed is does not change 'b'.

Full disclosure: I am the developer of memory_graph.
akbarza likes this post
Reply


Messages In This Thread
RE: difference between forms of input a list to function - by bterwijn - Feb-21-2024, 08:02 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  user input values into list of lists tauros73 3 1,163 Dec-29-2022, 05:54 PM
Last Post: deanhystad
Information How to take url in telegram bot user input and put it as an argument in a function? askfriends 0 1,203 Dec-25-2022, 03:00 PM
Last Post: askfriends
  set.difference of two list gives empty result wardancer84 4 1,600 Jun-14-2022, 01:36 PM
Last Post: wardancer84
  Showing an empty chart, then input data via function kgall89 0 1,025 Jun-02-2022, 01:53 AM
Last Post: kgall89
  input function question barryjo 12 2,942 Jan-18-2022, 12:11 AM
Last Post: barryjo
  function with 'self' input parameter errors out with and without 'self' called dford 12 3,314 Jan-15-2022, 06:07 PM
Last Post: deanhystad
  Problem with input after function luilong 10 4,272 Dec-04-2021, 12:16 AM
Last Post: luilong
  Exit function from nested function based on user input Turtle 5 3,057 Oct-10-2021, 12:55 AM
Last Post: Turtle
Star I'm getting syntax error while using input function in def. yecktmpmbyrv 1 2,040 Oct-06-2021, 09:39 AM
Last Post: menator01
  Input function cutting off commands at spaces. throwaway34 3 2,275 May-12-2021, 06:40 AM
Last Post: throwaway34

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020