Skip to content
Advertisement

Python: smallest number in list

I’m new to python and i don’t know how to find the smallest number in each array. The input is [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ] and the output should be [2, 3, 5, 1]. I have try this:

x = [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]
minimal = x[0]
  for i in range(len(x)):
      if (x[i]< minimal):
          minimal = x[i]
print(minimal)

And the output that i got is [2], i have no idea about this. Please help me…

Advertisement

Answer

First, we need to get individual lists from list x using for lst in x:. Then we find the minimum value of that list using min() function & append it to your minimal list using minimal.append(min(lst)), then print the final minimal list Now you will have your output as [2, 3, 5, 1]

Now try & understand this code:

x = [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]

minimal = []

for lst in x:
    minimal.append(min(lst))
print(minimal)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement