0

I have a list which we can iterate using for loop as follows:

myList = ['A', 'B', 'C', 'D']
for elem in myList:
    print("Element = %s" % elem)

The above will iterate the list in sequence. But I want do that in parallel. How to do that? Is it possible to do so without creating any new method? Is it necessary to create any multithreading or multiprocessing?

Please advise. Any example is appreciated

Thanks.

7
  • What exactly do you mean by 'parallel'? Commented Mar 16, 2021 at 10:35
  • stackoverflow.com/questions/35319025/… Commented Mar 16, 2021 at 10:35
  • You can use the threading library, create multiple threads and run different operations in each Commented Mar 16, 2021 at 10:36
  • @ Ismail Hafeez , I want to iterate the loop simultaneously for all the items instead of running them in sequence.
    – RDX
    Commented Mar 16, 2021 at 10:37
  • @benpomeroy9 , is there any example for the same?
    – RDX
    Commented Mar 16, 2021 at 10:37

2 Answers 2

3

In response to a comment I added, you can use threading to have to functions performing at the same time. You need to import the library, define two functions you want to run simultaneously, then create the threads.

import threading

def func1():
    #Perform one action here
    myList = ['A', 'B', 'C', 'D']
    for elem in myList:
        print("Element = %s" % elem)

def func2():
    #Perform one action here
    myList = ['E', 'F', 'G', 'H']
    for elem in myList:
        print("Element = %s" % elem)

t1 = threading.Thread(target=func1) #Create first thread running the function func1
t2 = threading.Thread(target=func2) #Create second thread running the function func2

#Start the threads
t1.start()
t2.start()
4
  • Thanks for the example. So in this case, will the iteration over the list ['A', 'B', 'C', 'D'] happen parallelly? I feel will it print all the 5 values simultaneously? Or the 2 threads t1 and t2 will parallelly in which each list will be iterated in sequence?
    – RDX
    Commented Mar 16, 2021 at 10:55
  • @RDX have you tried running the code provided in this answer a few times?
    – jfaccioni
    Commented Mar 16, 2021 at 11:44
  • @jfaccioni, yes did that.
    – RDX
    Commented Mar 16, 2021 at 11:56
  • @RDX did this answer help you? If so mark it as correct so others can see the answer easily! Commented Mar 26, 2021 at 14:16
-1

If you want to iterate it in parallel, you have to implement some kind of multitasking. For example, you can create 2 threads, one for the first half ond the other for the second half ([A,B], [C,D])

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.