2

I am new to Python, so apologize if the question is very simple.

I want to append a value to a list. However, I need to check if the value computed is less than 5000.

If the value is less than 5000 then append the computed value, else append 5000. How can I do this?

e.g

mylist.append(a*list1[t]+b*list1[t+1])

My current approach:

if a*list1[t]+b*list1[t+1] < 5000:
    mylist.append(a*list1[t]+b*list1[t+1])
else:
    mylist.append(5000)

Can I do this in one line?

MarianD
  • 9,720
  • 8
  • 27
  • 44
MAIGA
  • 29
  • 2

1 Answers1

6

You can use the builtin min() method.

Let A = a*list1[t] and B = b*list1[t+1].

With your approach:

if A + B < 5000:
    mylist.append(A + B)
else:
    mylist.append(5000)

With min() approach:

mylist.append(min((A + B), 5000))
MarianD
  • 9,720
  • 8
  • 27
  • 44
Felipe
  • 90
  • 3