why I cant append a row in a list?

78 Views Asked by At

I have 2 dim list, which contains duplicated elements in some lists as shown below

  myData=[['a',1,10],['b',2,20],['a',3,30],['a',4,40]]

I want to do:

  • create 2 empty lists called(duplicatedLists, uniqueLists)
  • read the first column/(element) in each list of myData
  • if the first column/element does not exist in uniqueLists, then append the entire row to uniqueLists
  • if it exists in uniqueLists, then append the entire row to duplicatedList(do not append to uniqueList)

I wrote the code below:

duplicatedLists=[]

uniqueLists=[]

myData=[['a',1,10],['b',2,20],['a',3,30],['a',4,40]]

for row in myData:

    print(row[0])


    if(row[0] not in uniqueLists):

        uniqueLists.append(row)

    else:

        duplicatedLists.append(row)

print(uniqueLists)

print(duplicatedLists)


so my result should be:

    uniqueLists=[['a',1,10],['b',2,20]]

    duplicatedLists=[[['a',3,30],['a',4,40]].

however I get this result:

[['a', 1, 10], ['b', 2, 20], ['a', 3, 30], ['a', 4, 40]]



[]
1

There are 1 best solutions below

2
Rakesh On

You have issue in this line if(row[0] not in uniqueLists): You are checking for first element but you are appending the entire sub-list in to uniqueLists list

Instead Try:

myData=[['a',1,10],['b',2,20],['a',3,30],['a',4,40]]
duplicatedLists=[]
uniqueLists=[]
check_val = set()
for i in myData:
    if i[0] not in check_val:     #Check if value in set. 
        uniqueLists.append(i)
        check_val.add(i[0])       #! Add only first element to perform check. 
    else:
        duplicatedLists.append(i)

print(uniqueLists)       #[['a', 1, 10], ['b', 2, 20]]
print(duplicatedLists)   #[['a', 3, 30], ['a', 4, 40]]