-1

I just began learning Python. So I am a beginner. I have a question about "for statement." I think I still don't know the rule of it. Please see below.

example:

list1 = []
list2 = []

def forStatement():
    for i in range(3):
        for j in range(5, 7):
            list2.append(j)
        list1.append(list2)
    return list1

The result I am looking for is;

[[5, 6], [5, 6], [5, 6]]

But when I run that code, it turns out like this.

[[5, 6, 5, 6, 5, 6], [5, 6, 5, 6, 5, 6], [5, 6, 5, 6, 5, 6]]

Can anyone help me? How can I get that result? Thank you so much.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
J.Shim
  • 71
  • 1
  • 5
  • 1
    This a FAQ of Python, I believe there is a duplicate... – scriptboy Mar 01 '18 at 03:18
  • 3
    Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Kind Stranger Mar 01 '18 at 03:37

3 Answers3

3

You are almost correct, the only problem with your code is that you keep adding elements to list2. Instead, you should create a new list every time:

list1 = []

for i in range(3):
    list2 = []
    for j in range(5, 7):
        list2.append(j)
    list1.append(list2)
damores
  • 2,251
  • 2
  • 18
  • 31
  • If my answer helped solve your problem, please consider marking it as the accepted answer, thanks! – damores Mar 01 '18 at 03:26
0

You are appending in the loop, where you want to reset list2 each iteration of i

list1 = []

for i in range(3):
    list2 = []
    for j in range(5, 7):
        list2.append(j)
    list1.append(list2)

>>> print list1
[[5, 6], [5, 6], [5, 6]]
Jared B.
  • 106
  • 4
0

For your code, list1 is a container object which takes references to an object to which list2 is bound. (Usually, such a object is mentioned as list2 for brevity.) After the execution of the code, list1 finally contains three elements (i.e. references to list2) and list2 obviously contains triple (outer loop executed 3 times) consecutive 5, 6 (every execution of inner loop append 5 and 6 to list2).

The following code should be what you expect:

list1 = []

list2 = None

for i in range(3):
    list2 = [] # To create a new empty list object and let it bound to the variable list2 every outer loop.
    for j in range(5, 7):
        list2.append(j)
    list1.append(list2)

In this code, after the execution, list1 contains three elements that are distinct objects. But they were all bound to the variable list2 in the past.

Dummmy
  • 688
  • 1
  • 5
  • 11