How to Loop a string list?

56 Views Asked by At

I’m brand new to coding and have been teaching myself Python. I have been trying to create multiple shopping list, that I can print out in a f-string. My code keeps repeating the f-string by the number of items in the list. No matter what I try, I can’t get the list of items to print.

I would like to be able to create individual shopping list. that I can add and take away items from, that automatically update the f-string when printed.

This is what I have:

Dads_shopping_list = ["Body Wash", "Soda", "Water", "Candy Bar"]

Izaiahs_shopping_list = ["Apples", "Wings", "Chips"]

for Dad in Dads_shopping_list:
    for Izaiah in Izaiahs_shopping_list:
        print(f"Hey can you pick up [Dad] for Dad. And can you bring me back [Izaiahs].")
2

There are 2 best solutions below

3
Jab On

This is what zip is for. It iterates multiple iterables at once:

for Dad, Izaiah in zip(Dads_shopping_list, Izaiahs_shopping_list):
    print(f"Hey can you pick up {Dad} for Dad. And can you bring me back {Izaiahs}.")
0
KRG On

I assume that you need the output like 'Hey can you pick up -,-,-,dad list items,-,- for Dad. And can you bring me back -,-,-, Izaiah list items,-,- '. You can try the below code by joining the list.

Dads_shopping_list = ["Body Wash", "Soda", "Water", "Candy Bar"]
Izaiahs_shopping_list = ["Apples", "Wings", "Chips"]

print("Hey can you pick up " + ','.join(Dads_shopping_list)+ " for Dad. And can you bring me back " +  ','.join(Izaiahs_shopping_list) + ".")

output

Hey can you pick up Body Wash,Soda,Water,Candy Bar for Dad. And can you bring me back Apples,Wings,Chips.