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

Advertisements

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

[‘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']

Leave a Reply Cancel reply