aNameNoob aNameNoob - 1 year ago 83
Python Question

Making a loop with lists

I am new to Python and would like to create a print function that repeats itself for each item in a list (this is only an example my actual code will be for something else)

cars.list = [Honda, Chevrolet, Suzuki, Ford]

price.list = [5600, 11500, 6600, 1020]

The prices and car lists are in the same order so Honda is $5600, Chevrolet is 11500 ect. I'd like it to run a loop for each of the cars that prints this:

while count in cars.list:
print("The car type is" Honda/Chev ect. "The price is" 5600, 11500 ect"

I want it to repeat the loop for as many cars are in the
, as I will add an option for the user to add more cars so the program cannot rely on knowing the specific cars in a list and copying the print statement for each one. It needs to repeat the print statement for every car, replacing the price and car type each time with the next one in the list.

I kinda need help ASAP as this needs finishing quick. Thanks :D

Answer Source

You can use zip to associate the cars and prices together in an iterator of tuples, then iterate over those tuples while printing what you want.

cars = ['Honda', 'Chevrolet', 'Suzuki', 'Ford']
prices = [5600, 11500, 6600, 1020]

for car, price in zip(cars, prices):
    print('The car type is {} and the price is {}.'.format(car, price))


The car type is Honda and the price is 5600.
The car type is Chevrolet and the price is 11500.
The car type is Suzuki and the price is 6600.
The car type is Ford and the price is 1020.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download