Reputation: 9
I'm very new to programming and trying to combine a list and tuple into a new list:
I'd be very grateful for a simple solution and also a brief explanation why my attempt only returns a value for cloth (I entered range 0:5 but it seems just to return element 4, cloth and its price)
import random
goods = ("Silk", "Gems", "Wool", "Hide", "Cloth", "Iron")
def set_prices ():
price_s = random.randrange(180,300)
price_g = random.randrange(250,800)
price_w = random.randrange(1,5)
price_h = random.randrange(5,18)
price_c = random.randrange(20,50)
price_i = random.randrange(50,150)
prices = [price_s,price_g,price_w,price_h,price_c,price_i]
for n in range (0,5):
offer = [(goods[n],prices[n])]
print (offer)
set_prices()
Upvotes: 0
Views: 85
Reputation: 765
The problem is that range(0,5)
will only produce 0,1,2,3,4
, as the 5
is excluded. An easy solution is to use range(len(goods))
, to produce a range with the same number of values of goods:
for n in range(len(goods)):
...
Alternatively, you could use zip
to iterate through both lists simultaneously:
for offer in zip(goods,prices):
print(offer)
This produces output as a tuple:
('Silk', 276)
('Gems', 486)
...
but can be converted to a list with list(offer)
:
['Silk', 188]
['Gems', 620]
['Wool', 2]
['Hide', 14]
['Cloth', 38]
['Iron', 130]
Upvotes: 2