0

How do I check if the elements of multiple lists inside a list are identical? The following code is from Checking if all elements of a List of Lists are in another List of Lists Python but it only counts the number of list in my list, not the elements the lists inside the list. Thanks in advance!

x.count(x[0]) == len(x)
Jay Man
  • 31
  • 6

3 Answers3

0

1)You can use this:

for i in l:
    if len(set(i)) != 1:
       print('not ok')
       break
else:
    print('ok')

2) it is better to use one line statement for this purpose like below:

all([len(set(i)) == 1 for i in l])

l is list of lists.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0
for prev, next in zip(l[:-1],l[1:]):
    if prev != next:
        return False
return True
Logan
  • 1,614
  • 1
  • 14
  • 27
  • I keep rereading the question and I'm no longer sure what it is asking, so I can't tell if my answer is right. Please provide more details, if you can. – Logan Jun 24 '18 at 06:20
0

Create an intermediate list storing 1 if all elements of a sublist are same. Later, check if lengths of original and intermediate lists are same:

lst = [[2,2,2], ['d']]

inter = [1 for x in lst if x[1:] == x[:-1]]
if len(lst) == len(inter):
    print(True)
else:
    print(False)

Or you just need:

if all([1 if x[1:] == x[:-1] else 0 for x in lst]):
    print(True)
else:
    print(False)
Austin
  • 25,759
  • 4
  • 25
  • 48