-1

I have the following code

pop = [[2.162840682206156, 1.8735137437504137, 1.0432493688065905],
       [2.8316083260339413, 1.3335260337446606, 0.7503595302921512]]

print '==>pop :: {}'.format(pop)

def serial(ind):
    ssgs = ssgs.SSGS()
    pheno = ssgs.s_SGS(ind)
    print "serial :: {}".format(pheno.serial)
    return pheno.serial,

for i in range(len(pop)):
    print '==>pop1 :: {}'.format(pop[i])
    value = serial(pop[i])
    print '==>pop2 :: {}'.format(pop[i])

after passing the list pop to the serial() the value of pop becomes None,

==>pop :: [[2.162840682206156, 1.8735137437504137, 1.0432493688065905], [2.8316083260339413, 1.3335260337446606, 0.7503595302921512]]

==>pop1 :: [2.162840682206156, 1.8735137437504137, 1.0432493688065905]
serial :: [0, 0, 3]
==>pop2 :: [None, None, None]

==>pop1 :: [2.8316083260339413, 1.3335260337446606, 0.7503595302921512]
serial :: [0, 0, 3]
==>pop2 :: [None, None, None]

Update: The output that I am expecting is somthing like this i.e. the value of pop should not change

==>pop1 :: [2.8316083260339413, 1.3335260337446606, 0.7503595302921512]
    serial :: [0, 0, 3]
 ==>pop2 :: [2.8316083260339413, 1.3335260337446606, 0.7503595302921512]

update: ssgs is a job scheduling class where it finds the start time of each task.

If I am correct a copy of pop is sent to the serial(), then why the values of pop is replaced by None? Why the program behaves this way?

Corey
  • 111
  • 2
  • 14

1 Answers1

1

Because lists are mutable data types. And these in Python pass their pointer around (like any regular objects) instead of acting as a single unit like strings or ints. which automatically copy themselves.

This allows you to do just that. Pass a list into a function and modify it from in there. This has a lot of benefits.

So, if you are going to pass a list into a function that is doing something to it, but you do not want the original list changed, you have to copy the original to be used locally in the function only:

clist = my_list[:] # Use slicing to make a copy of my_list
serial(clist)

To use it just locally do not assign it, just do serial(my_list[:])

P.S. Do not call your list pop, it is confusing as pop is a method of the list() instances.

Dalen
  • 4,128
  • 1
  • 17
  • 35