python - List index out of range and random number to choose an item in list -
i need make list of iphone models string using .split()
.
that's not problem, have use random number 0-9 pick word, display 3 random words using while/for loop.
in code, when enter:
import random iphone = 'original 3g 3gs 4 4s 5 5c 5s 6 6plus'.split() z = 0 while z < 4: y in range (1,3): x in iphone: x = random.randint(0,9) print (iphone[x])
it says:
traceback (most recent call last): file "c:\users\zteusa\documents\az_wordlist2.py", line 15, in <module> print (iphone[x]) indexerror: list index out of range
i'm not sure whats causing this.
both arguments random.randint
inclusive:
>>> import random >>> random.randint(0, 1) 1 >>> random.randint(0, 1) 0 >>>
so, when x = random.randint(0,10)
, x
equal 10
. list iphone
has ten items, means maximum index 9
:
>>> iphone = 'original 3g 3gs 4 4s 5 5c 5s 6 6plus'.split() >>> len(iphone) 10 >>> iphone[0] # python indexes start @ 0 'original' >>> iphone[9] # max index 9, not 10 '6plus' >>> iphone[10] traceback (most recent call last): file "<stdin>", line 1, in <module> indexerror: list index out of range >>>
you need do:
x = random.randint(0, 9)
so x
within range of valid indexes iphone
.
regarding comments, said need print 3 random items list. so, this:
import random iphone = 'original 3g 3gs 4 4s 5 5c 5s 6 6plus'.split() z = 0 while z < 3: x = random.randint(0,9) print (iphone[x]) z += 1 # remember increment z while loop exits when should
Comments
Post a Comment