Extreme_d1
Extreme_d1

Reputation: 13

How to use list comprehension to simplify code

I'm solving a problem on codewars, and I needed to create a function that found the smallest number in an array. This is my code:

def find_smallest_int(arr):
    smallest_number = arr[0]
    for num in arr:
        if num < smallest_number: 
            smallest_number = num
        else:
            continue
    return smallest_number

My answer is correct. But I want to know how I could simplify my code using list comprehension (I'm fairly new to coding). This is what I tried, but I received an error:

def find_smallest_int(arr):
    smallest_number = arr[0]
    x = [smallest_number for num in arr if num < smallest_number , smallest_number = num] 

What would be the correct way to use list comprehension in this case?

Upvotes: 0

Views: 141

Answers (2)

poison_pwn
poison_pwn

Reputation: 96

List comprehensions are used to apply a simple function to an iterable and returns a list

list_ = [num**2 for num in numbers]

If a function is more complex, define the function (or use a lambda expression) and use map() to apply that function like

new_list = list(map(function, iterable))

or like

new_list = list(map(lambda num: num**2, num_list))

Upvotes: 0

Eeshaan
Eeshaan

Reputation: 1635

In Python you can just use the min function like so

min(arr)

It'll return the smallest value in the list. If for some reason you don't want to do it this way, then write your own function like so

def min_of_arr(nums):
  min_num = float('inf') # +infinity
  for num in nums:
    if num < min_num:
      min_num = num
  return min_num

P.S. List comprehension is used to get a list, not a single / atomic value.

Upvotes: 5

Related Questions