-1

so I am trying to create a list that have different list as it element the for loop bellow will extend an element to the bag then append it to the list bag and finally remove the extended element to repeat the cyclec the bag contains these elements ['B', 'D'] and the rf contains these elements ['C', 'A', 'G', 'E']

list_bag = []

for  i in range(len(rf)) :
    bag.extend(rf[i])
    a= bag
    list_bag.append(a)
    bag.pop()
print(list_bag)

the out put I am trying to archive is this : [['B', 'D','A'], ['B', 'D','E'], ['B', 'D','F'], ['B', 'D','C']] but the code keep on giving me this [['B', 'D'], ['B', 'D'], ['B', 'D'], ['B', 'D']]

any suggestion ?

phuc
  • 9
  • 1
  • `NameError: name 'rf' is not defined`; similar, `NameError: name 'bag' is not defined`. Your example code is not reproducible, and it's anyone's guess whether `bag` is set to an empty list, or you set it to be equal to `list_bag`. (Given your result, the second option is likely.) – 9769953 Nov 30 '22 at 15:10

1 Answers1

0

You can accomplish what you want with a list comprehension.

list_bag = [bag + [item] for item in rf]
Sterling
  • 432
  • 2
  • 9