Python Forum
How to reduce the following code to run in sequence?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to reduce the following code to run in sequence?
#1
Hello all,
I would like to reduce the following python code.
I have one list:
a=[one, two, three, four]
And the following statement s are all true

if a[0] in b:
     print(a[1])
if a[1] in b:
     print(a[2])
if a[2] in b:
     print(a[3])
if a[3] in b:
     print(a[0])
How can I reduce this to two lines of code and still to run in sequence? It will permit list a to be of "n" length and I will not have to add them individually.
Reply
#2
It would help to know what b is.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
b=["five","four","three","two","one"]
I've said is true.
Reply
#4
Here is a couple of examples
a = ['one','two','three','four']
b = ['one','two','three']
# First
for i in range(len(a)):
    if a[i] in b:
        print(f'{a[i]} is in b')
    else:
        print(f'{a[i]} in not in b')

#Second
[print(a[i]) for i in range(len(a)) if a[i] in b]
Output:
1st example one is in b two is in b three is in b four in not in b 2nd example one two three
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#5
Thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  reduce nested for-loops Phaze90 11 1,891 Mar-16-2023, 06:28 PM
Last Post: ndc85430
  Adding values with reduce() function from the list of tuples kinimod 10 2,637 Jan-24-2023, 08:22 AM
Last Post: perfringo
  How do I reduce the time to Invoke Macro via Python? JaneTan 1 2,130 Dec-28-2020, 06:46 AM
Last Post: buran
  Why the multithread does not reduce the execution time? Nicely 2 2,483 Nov-23-2019, 02:28 PM
Last Post: Nicely
  Please suggest python code to format DNA sequence FASTA file rajamdade 4 3,174 Oct-24-2019, 04:36 AM
Last Post: rajamdade
  Help to reduce time to execute the code prakash52kar 1 2,222 Oct-14-2019, 10:56 AM
Last Post: scidam
  Python- Help with try: input() except ValueError: Loop code to start of sequence Aldi 2 6,302 Mar-08-2018, 03:46 AM
Last Post: Larz60+
  Reduce the code for if statements chris0147 8 4,646 Mar-03-2018, 02:20 AM
Last Post: Larz60+
  Question about code sequence tsetsko 2 2,928 Sep-03-2017, 11:45 AM
Last Post: tsetsko

Forum Jump:

User Panel Messages

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