Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need to loop through a list and perform operations between each object

So I need to loop through a list and in between each object and the next, perform an operation, whether it’s addition, subtraction, or multiplication, however each time I iterate, my code only ends up using one operator, and not a combination.

Here’s an example code

list_test = ['test1', 'test2', 'test3', 'test4]
for x in list_test:
    operation = random.choice(['+', '-', '*'])
    if operation == '+': 
        new_list = "".join(str(list_test).replace(',', operation))
    else:
        new_list = "".join(str(list_test).replace(',', operation))
print(new_list)

and this is my output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[‘test1’+ ‘test2’+ ‘test3’ + ‘test4]

Instead I ideally want something like

[‘test1’+ ‘test2’- ‘test3’ *’test4]

or

[‘test1’+ ‘test2’ * ‘test3’ + ‘test4]

>Solution :

    list_test = ['test1', 'test2', 'test3', 'test4']
    new_list = []
    for x in list_test:
        operation = random.choice(['+', '-', '*'])
        new_list.append(x)
        new_list.append(operation)
    print(new_list)

Output

['test1', '*', 'test2', '-', 'test3', '-', 'test4', '+']

EDITED

import random
list_test = ['test1', 'test2', 'test3', 'test4']
new_list = []
for idx, x in enumerate(list_test):
    operation = random.choice(['+', '-', '*'])
    new_list.append(x)
    if idx < len(list_test)-1:
        new_list.append(operation)

print(new_list)

Output

['test1', '+', 'test2', '*', 'test3', '-', 'test4']

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading