Skip to content
Advertisement

In Python, I want to add a number to each element in a list, but I get [[0,1],2] instead of [0,1,2]. How to fix this?

I have

listB=[[0,1],[1,2]]

listall=[0,1,2,3]

For each element in listB, I want to extend it to a length-3 element by adding a number that is in listall but not in this element. My desired output is the following list:

listC=[[0,1,2],[0,1,3],[1,2,3]]

As a first step, I tried the following code:

import numpy as np

listB=[[0,1],[1,2]]
listall=range(4)
listC=[]
for b in listB:
    difb=set(listall)-set(b)
    for i in difb:
        listC.append([b,i])
print(listC)

However, the output I got is:

[[[0,1],2],[[0,1],3],[[1,2],0],[[1,2],3]]

This is far from what I wanted. As each element in this output list has a subarray nested in it, also the numbers in each element are not ordered. I need to at least turn it to [[0,1,2],[0,1,3],[0,1,2],[1,2,3]] first (and then get rid of the duplicates). What’s the fastest (most efficient) way to achieve it? Thanks!

Advertisement

Answer

You need to unpack the items in b when creating the new list

listC.append([*b,i])

or if its easier to understand, add a new list with i to list b

listC.append(b + [i])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement