Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Problems with For Loops and Lists
#1
Hello all,
I am beginner and I can't find the mistake in my code.

Starting with a list list_item = [0, 0, 0] I want modify every single element sequentially.
I want also that each modified element will become an element of the list called list_with_list_items.

I wrote this code:

list_item = [0, 0, 0] 
list_with_list_items=[] 
for n0 in range(0, 5): 
    list_item [0] = n0+1 
    for n1 in range(n0+1, 6): 
        list_item [1] = n1+1 
        for n2 in range(n1+1, 7): 
            list_item [2] = n2+1 
            print(str(list_item)) 
            list_with_list_items.append(list_item) 
print(str(list_with_list_items)) 
but the output is:
[[5, 6, 7], [5, 6, 7], [5, 6, 7], …., [5, 6, 7], [5, 6, 7], [5, 6, 7]]

what I want is:
[[1, 2, 3], [1, 2, 4], [1, 2, 5], …., [4, 5, 7], [4, 6, 7], [5, 6, 7]]

but I can't find the mistake.

Thank you in advance for your help.
Quote
#2
This is because of reference-counting model of object management in Python. list_item points to "container" that initially
stores [0,0,0]. You are changing list_item in a loop, but since lists are mutable in Python, Python doesn't create new object each time you change list_item elements. list_item points to the same container. So, list_with_list_items accumulates references to the same container, which final state is [5, 6, 7]. You need to force Python to create a new list object when appending data to list_with_list_items. This could be easily done by replacing list_item with list_item[:] in line #10 of your code.
snippsat likes this post
Quote
#3
Amazing, thank you!!!
I would never have thought of it.
Best regards
MB
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Multiprocessing using on multiple for loops Staph 3 111 Jul-28-2019, 07:24 AM
Last Post: ThomasL
  Having problems using 'or' in a 'if' statement? umut3806 2 224 Jul-21-2019, 11:33 PM
Last Post: umut3806
  coding help lists, loops, and if statement ilondire05 5 244 Jul-19-2019, 07:32 AM
Last Post: perfringo
  Problems with "re.fullmatch" AlanT 8 519 May-18-2019, 04:45 PM
Last Post: AlanT
  need some help with loops s138733 2 211 May-07-2019, 03:54 PM
Last Post: gontajones
  Importing a CSV loops to infinity in python bluethundr 2 388 May-03-2019, 03:28 PM
Last Post: bluethundr
  Problems with calculator muachihiyo 3 243 May-02-2019, 06:12 PM
Last Post: ichabod801
  Converting to exe problems francisco_neves2020 12 653 Apr-20-2019, 11:58 PM
Last Post: francisco_neves2020
  adding lists to lists? ivinjjunior 5 361 Apr-15-2019, 07:41 PM
Last Post: ivinjjunior
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 246 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:


Users browsing this thread: 1 Guest(s)