-1

Let's say I have this two functions:

lst = []
def function1(request):
    lst = ['12','10']
    return HttpResponse(...)

def function2(request):
    qry = SampleModel.objects.filter(id__in=lst)
    return HttpResponse(...)
Sachi Tekina
  • 1,800
  • 5
  • 28
  • 50

2 Answers2

0

Use global. Here's one sample:

lst = [2,3]
def function1():
    global lst  # Guide lst to the global list that is already available
    print('lst = {}'.format(lst))
    lst = ['12','10']

print('lst = {}'.format(lst))
function1()
print('lst = {}'.format(lst))

You will see the following output:

lst = [2, 3]
lst = [2, 3]
lst = ['12', '10']
-1

Check first example.

global lst
lst=[]
def function1():

    lst.append(6)
    print(lst)

def function2():
    lst.append(7)
    print(lst)

function1()
function2()

output:-

C:\Python34\python.exe "C:/Users/akthakur/PycharmProjects/Learning python/testing.py"
[6]
[6, 7]

Here lst is declared as global and is used in function 1 and when used in function 2,same lst was used so the output.

Second Example

global lst
lst=[]
def function1():
    lst=[7,8]
    lst.append(6)
    print(lst)

def function2():
    lst.append(7)
    print(lst)

function1()
function2()

Output

C:\Python34\python.exe "C:/Users/akthakur/PycharmProjects/Learning python/testing.py"
[7, 8, 6]
[7]

Now as you defined in function1 lst=[7,8] so this creates a new local list lst and in function1 same was used(local version) and in function2 when you again called lst,its global version was called.[this is what you are doing.]

So rather then declaring new local list as lst = ['12','10'] ,append your values to the existing list defined outside the function and declare the same as global.

thinkingmonster
  • 5,063
  • 8
  • 35
  • 57