-3

I have a problem with lists in Python. Based on below code written in Pycharm and using pypy interpreter, when I clear the first list the second list loses its given values.

def test():

    first_list = []
    second_list = []

    for i in range(10):
        first_list.append(i)

    if len(first_list)>1:
        second_list.append(first_list)
        first_list.clear()

    for j in range(100,105):
        first_list.append(j)

    if len(first_list)>1:
        second_list.append(first_list)
        first_list.clear()

    print(second_list)


#output:
[[], []]
bbnumber2
  • 643
  • 4
  • 18
Reezaro
  • 1
  • 1
  • 1
    Does this answer your question? [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – bbnumber2 Jan 16 '21 at 00:24
  • tho I know the difference between reference and value ,I am confused how to keep old numbers in the second_list when clearing the first_list. – Reezaro Jan 16 '21 at 00:45
  • @Reezaro you keep appending *the same list*, `second_list.append(first_list)` so of course, when you clear the list you've appending, the outer list contains several references to the same (empty) list – juanpa.arrivillaga Jan 16 '21 at 01:02
  • well noted. thank you – Reezaro Jan 17 '21 at 01:31

1 Answers1

0

Copy vs reference issue.

first_list = []
second_list = []

for i in range(10):
    first_list.append(i)

if len(first_list)>1:
    second_list.append(first_list[:])
    first_list.clear()

for j in range(100,105):
    first_list.append(j)

if len(first_list)>1:
    second_list.append(first_list[:])
    first_list.clear()

print(second_list)
goalie1998
  • 1,427
  • 1
  • 9
  • 16