Python Forum

Full Version: append not working as expected
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I am trying to create a list (called megalist) of all of the 3 digit combinations from the list of numbers called numbers. I think the logic is sound (I am testing the process with print commands and they seem to suggest all is well.) But for some reason the append to is not simply appending. Each time a new 3-digit combo is created and added to megalist it replaces the previous combos collected with the newest combo as well. I can't figure out why!
So,
megalist begins empty.
First combo is created [1,3,5]
megalist becomes [[1,3,5]]
next combo is created [1,3,7]

numbers=[1,3,5,7,9,11,13,15]
megalist=[]
list_of_3=[-1,-1,-1]
for first in range(len(numbers)-1): #selecting first number from the 1 till 11
  first_num=numbers[first]
  list_of_3[0]=first_num
  print('list of 3 is ', list_of_3)
  for second in range(1+numbers.index(list_of_3[0]),len(numbers)): #selecting second 3 to 13
    second_num = numbers[second]
    list_of_3[1]=second_num
    print('list of 3 is ', list_of_3)
    for third in range(1+numbers.index(list_of_3[1]),len(numbers)+1): #selecting 3rd 5 to 15
      third_num = numbers[third]
      print('3rd number is ', third_num)
      list_of_3[2]=third_num
      print('list of 3 is ', list_of_3)
      megalist.insert(0,list_of_3)
      print('combos = ',megalist)
You aren't appending, you are redefining things.

what you want it is
megalist.append(list_of_three)
This will tack it onto the end.
(Apr-09-2020, 03:19 AM)michael1789 Wrote: [ -> ]You aren't appending, you are redefining things.

what you want it is
megalist.append(list_of_three)
This will tack it onto the end.
They insert the list always in position 0. Technically not appending, you are right, but that is not the cause of the problem. Even if they append, the problem will persist.

@teachinggeek: Lists are mutable object. Basically you insert the same object over and over again. Changes that you make affect also elements already inserted in the final list. That said, it's better to look at itertools.combinations()
>>> import itertools
>>> numbers=[1, 3, 5, 7, 9, 11, 13, 15]
>>> list(itertools.combinations(numbers, 3))
[(1, 3, 5), (1, 3, 7), (1, 3, 9), (1, 3, 11), (1, 3, 13), (1, 3, 15), (1, 5, 7), (1, 5, 9), (1, 5, 11), (1, 5, 13), (1, 5, 15), (1, 7, 9), (1, 7, 11), (1, 7, 13), (1, 7, 15), (1, 9, 11), (1, 9, 13), (1, 9, 15), (1, 11, 13), (1, 11, 15), (1, 13, 15), (3, 5, 7), (3, 5, 9), (3, 5, 11), (3, 5, 13), (3, 5, 15), (3, 7, 9), (3, 7, 11), (3, 7, 13), (3, 7, 15), (3, 9, 11), (3, 9, 13), (3, 9, 15), (3, 11, 13), (3, 11, 15), (3, 13, 15), (5, 7, 9), (5, 7, 11), (5, 7, 13), (5, 7, 15), (5, 9, 11), (5, 9, 13), (5, 9, 15), (5, 11, 13), (5, 11, 15), (5, 13, 15), (7, 9, 11), (7, 9, 13), (7, 9, 15), (7, 11, 13), (7, 11, 15), (7, 13, 15), (9, 11, 13), (9, 11, 15), (9, 13, 15), (11, 13, 15)]