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
14.4k12 gold badges50 silver badges62 bronze badges
1 Answer 1
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
14.4k12 gold badges50 silver badges62 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
MAIGA
That works. As a followup. Can you suggest improvement to this code
lang-py
var = a*list1[t]+b*list1[t+1]so you don't need to write (and compute) this twicemylist.append(a*list1[t]+b*list1[t+1] if a*list1[t]+b*list1[t+1] < 5000 else 5000)math.min, like this: pastebin.com/RNkU6q8p