Display the largest element in each row in a 2-D Array in Python

Display the largest element in each row in a 2-D Array in Python

Display largest element in a 2-D array

Array has n-rows and m-columns , here our task is to write a program to Display the largest element in each row in a 2-D Array in Python. Largest number can be find by max() function in python or by normal comparison. 

  • Sample input: a=[[1,2,3],[7,8,4],[56,34,87]]
  • Sample output: 3 8 87
  • Explanation: largest element in first row (1,2,3) is 3 , largest element in second row(7,8,4) is 8 , largest element in 3rd row (56,34,87) is 87

Working:

  • Step 1: Take inputs 
  • Step 2: traverse through it 
  • Step 3: using max function find out maximum element and print it.

Python code 

Solution 1:Program to Display the largest element in each row in a 2-D Array in Python

X = [[1,2,3],[7,8,4],[56,34,87]]
    
for i in range(len(X)):
    print(max(X[i])) 
3
8
87

Working:

  • Step 1: Take inputs
  • Step 2: Traverse through matrix
  • Step 3: Set variable m as any smallest value
  • Step 4: Traverse through each iterator 
  • Step 5: If this iterator is greater than maximum value m then update maximum value , else continue
  • Step 6: Print the maximum value

Solution 2:

X = [[1,2,3],[7,8,4],[56,34,87]]
    
for i in X:
    m=-1000000000
    for j in i:
        if j>m:
            m=j
        else:
            continue
    print(m) 
3
8
87