Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading