I'm a beginner here and could really use some help.
I have to determine whether all elements in a two-dimensional list is unique. For example, if given a two-dimensional list my_list = [[1,2,2],[4,5,2],[7,2,9]], I have to write a code that would say, "this list does not have all unique elements" because of the multiple 2s. I have to write code using nested loops.
Here is what I have so far:
my_list = [[1,2,2],[4,5,2],[7,2,9]]
for row in my_list:
for num in row:
if row.count(num) > 1:
print("Duplicate")
else:
print("No duplicate", num)
This code can detect the duplicate 2 in the first list of my_list, but not the second list.
To do it without flattening the list of lists first, you can use a set that keeps track of items that has been "seen", so that you can determine that there is a duplicate as soon as the current item in the iteration is already in the set:
seen = set()
for sublist in my_list:
for item in sublist:
if item in seen:
print('Duplicate')
break
seen.add(item)
else:
continue
break
else:
print('No duplicate')
You need to flatten the list of list and find for duplicates. You can flatten a list of lists using itertools.chain.from_iterable
from itertools import chain
my_list = [[1,2,2],[4,5,2],[7,2,9]]
flat=list(chain.from_iterable(my_list)
if len(flat)==len(set(flat)):
print('No dups')
else:
print('Dups found')
Edit: Using for-loops without flattening
count={}
dups=False
for lst in my_list:
for k in lst:
count[k]=count.setdefault(k,0)+1
if count[k]>1:
dups=True
break
if dups:
print("dups found")
break
else:
print('No dups')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With