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
14.4k12 gold badges50 silver badges62 bronze badges
asked Aug 29, 2018 at 17:05
6
  • 2
    suggestion: use var = a*list1[t]+b*list1[t+1] so you don't need to write (and compute) this twice Commented Aug 29, 2018 at 17:07
  • mylist.append(a*list1[t]+b*list1[t+1] if a*list1[t]+b*list1[t+1] < 5000 else 5000) Commented Aug 29, 2018 at 17:08
  • 2
    Use math.min, like this: pastebin.com/RNkU6q8p Commented Aug 29, 2018 at 17:11
  • @Chris_Rands I think this question should be re-opened, it's not necessarily a duplicate of the one you linked to. Commented Aug 29, 2018 at 17:12
  • 1
    @nnyby Just regular min() will do it but ok reopening Commented Aug 29, 2018 at 17:17

1 Answer 1

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
14.4k12 gold badges50 silver badges62 bronze badges
answered Aug 29, 2018 at 17:18
Sign up to request clarification or add additional context in comments.

1 Comment

That works. As a followup. Can you suggest improvement to this code

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.