Python Forum
[SOLVED] Simplify condition test in if block?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] Simplify condition test in if block?
#1
Thumbs Up 
Hello,

Out of curiosity, is there a way to simply an "if" line with multiple conditions?

if status == "1" \
	or status == "2" \
	…
	or status == "37":
		print("Yes")
Thank you.
Reply
#2
You could check if status matches an element in a collection.

if status in ["1", "2", "37"]:
    print("Yes")
Lists are fine for small collections. If the number of choices got to be too large, the lookup speed of a dict or a set might be useful.
Reply
#3
Nice.

Since the values are actually a long list of strings, I used a set:

status_set = {"String 1","String 3","String 4",\
		"String 5"}

if status in status_set:
	print("Hit!")
Thanks!
tester_V likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I want to simplify this python code into fewer lines, it's about string mandaxyz 5 2,115 Jan-15-2022, 01:28 PM
Last Post: mandaxyz
  How to test and import a model form computer to test accuracy using Sklearn library Anldra12 6 3,112 Jul-03-2021, 10:07 AM
Last Post: Anldra12
  else condition not called when if condition is false Sandz1286 10 5,843 Jun-05-2020, 05:01 PM
Last Post: ebolisa
  [HELP] Nested conditional? double condition followed by another condition. penahuse 25 7,898 Jun-01-2020, 06:00 PM
Last Post: penahuse
  How to write test cases for a init function by Unit test in python? binhduonggttn 2 3,104 Feb-24-2020, 12:06 PM
Last Post: Larz60+
  How to write test cases by Unit test for database configuration file? binhduonggttn 0 2,551 Feb-18-2020, 08:03 AM
Last Post: binhduonggttn
  How can i simplify this code Jezani_VIII 4 2,759 Aug-25-2019, 02:23 PM
Last Post: perfringo
  How to simplify square finding program? meknowsnothing 3 2,893 Jun-11-2019, 08:20 PM
Last Post: meknowsnothing
  Is it OK to use a context manager to simplify attribute access? nholtz 0 2,040 Jun-11-2019, 01:19 AM
Last Post: nholtz
  Dijkstra code - trying to simplify it grandpapa10 1 2,178 Jan-23-2019, 12:43 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020