How to find the smallest value in a list python

Last update on May 28 2022 13:15:45 (UTC/GMT +8 hours)

Write a Python program to get the smallest number from a list.

Example - 1 :

How to find the smallest value in a list python

Example - 2 :

How to find the smallest value in a list python

Example - 3 :

How to find the smallest value in a list python

Example - 4 :

How to find the smallest value in a list python

Sample Solution:

Python Code:

def smallest_num_in_list( list ): min = list[ 0 ] for a in list: if a < min: min = a return min print(smallest_num_in_list([1, 2, -8, 0]))

Sample Output:

-8

Flowchart:

How to find the smallest value in a list python

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to get the largest number from a list.
Next: Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.

What is the difficulty level of this exercise?

How can I safely create a nested directory?

On Python = 3.5, use pathlib.Path.mkdir:

from pathlib import Path Path("/my/directory").mkdir(parents=True, exist_ok=True)

For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:

Try os.path.exists, and consider os.makedirs for the creation.

import os if not os.path.exists(directory): os.makedirs(directory)

As noted in comments and elsewhere, there's a race condition - if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.

One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python's OSError):

import os, errno try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise

Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one - we could still be fooled.

Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.

Modern versions of Python improve this code quite a bit, both by exposing FileExistsError (in 3.3+)...

try: os.makedirs("path/to/directory") except FileExistsError: # directory already exists pass

...and by allowing a keyword argument to os.makedirs called exist_ok (in 3.2+).

os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.

Ref: https://bit.ly/3h8HYbu

To find the smallest value in a list with python, a solution is to use the function min():

>>> l = [4,7,1,4,1,6,9] >>> min(l) 1

which returns 1 here. To find the index, there is the function index(), example:

>>> l.index(min(l)) 2

Note: this function only returns the first index found. To find all the indexes of the smallest value (if there is several occurrences of the smallest value), we can do like in this example:

>>> indexes = [i for i, x in enumerate(l) if x == min(l)] >>> indexes [2, 4]

To find if there is several times the min value in the list, a solution is to use the python function count(), example:

>>> l = [4,7,1,4,1,6,9] >>> min_value = min(l) >>> min_value 1 >>> l.count(min_value) 2

it is then possible to write a simple function that returns the index(es):

>>> def get_indexes_min_value(l): ... min_value = min(l) ... if l.count(min_value) > 1: ... return [i for i, x in enumerate(l) if x == min(l)] ... else: ... return l.index(min(l)) ... >>> >>> get_indexes_min_value(l) [2, 4]

References

Hello there! This article is for beginners who wish to understand the basic code for finding the smallest number in Python. So let’s begin.

How to Find the Smallest Number in Python?

We aim to find the smallest number in Python of all the numbers given in a list.

Say if the list is: [32, 54, 67, 21]

The output should be: 21

In this article, we will understand 3 different methods to do this.

1. Using Python min()

Min() is a built-in function in python that takes a list as an argument and returns the smallest number in the list. An example is given below-

#declaring a list list1 = [-1, 65, 49, 13, -27] print ("list = ", list1) #finding smallest number s_num = min (list1) print ("The smallest number in the given list is ", s_num)

Output:

list = [-1, 65, 49, 13, -27] The smallest number in the given list is -27

This is one of the simplest methods to find the smallest number. All you need to do is to pass the list to min() as an argument.

2. Using Python sort()

Sort() is another inbuilt method in python that doesn’t return the smallest number of the list. Instead, it sorts the list in ascending order.

So by sorting the list, we can access the first element of the list using indexing and that will be the smallest number in that list. Let’s see the code:

#declaring a list list1 = [17, 53, 46, 8, 71] print ("list = ", list1) #sorting the list list1.sort () #printing smallest number print ("The smallest number in the given list is ", list1[0])

Output:

list = [17, 53, 46, 8, 71] The smallest number in the given list is 8

3. Using the ‘for’ loop

ls1 = [] total_ele = int (input (" How many elements you want to enter? ")) #getting list from the user for i in range (total_ele): n =int (input ("Enter a number:")) ls1.append(n) print (ls1) min = ls1[0] #finding smallest number for i in range (len (ls1)): if ls1[i] < min: min = ls1[i] print ("The smallest element is ", min)

In the above code, we are using two for loops, one for getting the elements of the list from the user and the second one for finding the smallest number from the list.

After getting the elements from the user, we define the first element of the list (at 0 index) as the smallest number (min). Then with the for loop, we compare each element of the list to the min and if any element is smaller than min, it becomes the new min.

This is how we get the smallest number from the user-given list.

The output for the above code is:

How many elements you want to enter? 4 Enter a number: 15 Enter a number: 47 Enter a number: 23 Enter a number: 6 [15, 47, 23, 6] The smallest number is 6

Conclusion

So, these were some methods to find the smallest number from the given list in python. Hope you understood this! Feel free to ask questions below, if any. Thank you! 🙂


Python list method min() returns the elements from the list with minimum value.

Syntax

Following is the syntax for min() method −

min(list)

Parameters

  • list − This is a list from which min valued element to be returned.

Return Value

This method returns the elements from the list with minimum value.

Example

The following example shows the usage of min() method.

#!/usr/bin/python list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200] print "min value element : ", min(list1) print "min value element : ", min(list2)

When we run above program, it produces following result −

min value element : 123 min value element : 200

python_lists.htm