List indices must be integers, not tuple (PYTHON)


#1

I am working on this code where two lists are to alternate printing an element from each list a random a mount of time but I keep getting the error “list indices must be integers, not tuple”. Im not sure where my error is. Here is my code:

from random import randint

cars = ['BMW', 'Benz','Tesla']

veggies = ['Broccoli', 'Carrots', 'Spinach']

for i in zip(cars, veggies):
    car = cars[i] + '\n'
    veg = veggies[i] + '\n'

    print(randint(4, 7) * (i[0] + '\n'))
    print(randint(4, 7) * (i[1] + '\n'))

#2

maybe you should print(i) to see what i actually has for values?


#3

This is what I get when I print i:

(‘BMW’, ‘Broccoli’)
(‘Benz’, ‘Carrots’)
(‘Tesla’, ‘Spinach’)


#4

that is a good step, what could be a next good step?


#5

How is the problem actually worded? Can you include the instruction text?


#6

Well, I’m thinking that it has something to do with the way lines 8 and 9 are written:

car = cars[i]
veg = veggies[i]

#7

" Each of the individual tasks job is to print their entire list, one car/veggie at a time, for a random number of times (generated at the beginning of task execution), between 4 and 7 times."


#8

can you share the exercise url?

well, you have seen what values i has now, so why do cars[i] and veggies[i]?


#9

Is this the output that is expected?

BMW Broccoli
BMW Broccoli
BMW Broccoli
BMW Broccoli
BMW Broccoli
Benz Carrots
Benz Carrots
Benz Carrots
Benz Carrots
Tesla Spinach
Tesla Spinach
Tesla Spinach
Tesla Spinach
Tesla Spinach
Tesla Spinach
Tesla Spinach

or are we supposed to randomize the whole ball of wax?

(Spoiler) Full blown random zips and list lengths
>>> from random import randrange, randint
>>> def shuffle(x):
	n = m = len(x)
	while n:
		while True:
			a, b = (randrange(m), randrange(m))
			if a != b: break
		x[a], x[b] = x[b], x[a]
		n -= 1
	return x

>>> def zip_shuffle(*args):
	p, q, mn, mx = args
	for i in zip(shuffle(p), shuffle(q)):
		u, v = i
		for _ in range(randint(mn, mx)):
			print (u, v)

			
>>> cars = ['BMW', 'Benz','Tesla']
>>> veggies = ['Broccoli', 'Carrots', 'Spinach']
>>> zip_shuffle(cars, veggies, 4, 7)
Tesla Broccoli
Tesla Broccoli
Tesla Broccoli
Tesla Broccoli
Tesla Broccoli
Tesla Broccoli
Tesla Broccoli
BMW Carrots
BMW Carrots
BMW Carrots
BMW Carrots
Benz Spinach
Benz Spinach
Benz Spinach
Benz Spinach
Benz Spinach
Benz Spinach
Benz Spinach
>>> 
Extra Study
>>> def zip_shuffle(*args):
	p, q, mn, mx = args
	for i in zip(shuffle(p), shuffle(q)):
		u, v = i
		for _ in range(randint(mn, mx)):
			print (u, v, end='  ')
		print ()


>>> zip_shuffle(list(range(10)), list(range(10)), 1, 9)
9 4  9 4  9 4  9 4  9 4  9 4  9 4  
7 1  7 1  7 1  7 1  7 1  7 1  7 1  
2 7  2 7  2 7  
3 6  3 6  3 6  3 6  3 6  3 6  3 6  3 6  3 6  
8 9  8 9  8 9  8 9  8 9  8 9  8 9  8 9  8 9  
1 5  
5 2  
0 0  0 0  0 0  0 0  
4 8  4 8  4 8  
6 3  6 3  6 3  6 3  6 3  6 3  
>>> 

The same 84 digit pattern would doubtless take forever to replicate.