create a loop that checks a 2d array to see if any single dimension contains all of the same elements in python

You can create a loop that checks a 2D array to see if any single dimension contains all of the same elements by comparing the length of the set of each row to 1. If the length is 1, then it means that all the elements in that row are the same. Here's a sample code that demonstrates how to achieve that:

main.py
arr = [
  [1, 2, 3],
  [4, 4, 4],
  [5, 6, 7],
  [8, 8, 8]
]

for row in arr:
    if len(set(row)) == 1:
        print("All values in the row are the same")
    else:
        print("Not all values in the row are the same")
223 chars
13 lines

Output:

main.py
Not all values in the row are the same
All values in the row are the same
Not all values in the row are the same
All values in the row are the same
148 chars
5 lines

In the code above, we have a 2D array called arr. We iterate through each row of this array using a for loop. For each row, we convert it into a set using the set() function, which eliminates any duplicate elements. We then compare the length of the set to 1 using an if statement. If the length is 1, we print All values in the row are the same. Otherwise, we print Not all values in the row are the same.

gistlibby LogSnag