TransWikia.com

Python cannot access list

Stack Overflow Asked by Forge Mods on November 28, 2020

colors = ["red", "green", "blue", "yellow", "black"]
for color in range(0,len(colors)):
    print(color[index])

Wondering why I am getting an error when trying to print color index and not sure how to fix or what to change, thanks

3 Answers

Because color is an integer, and you access it as if its a list.

You should probably wanted to access the color from colors like the following:

colors = ["red", "green", "blue", "yellow", "black"]
for color in range(0,len(colors)):
    print(colors[color])

The better way is to iterate over the colors list like:

colors = ["red", "green", "blue", "yellow", "black"]
for color in colors:
    print(color)

Correct answer by David S on November 28, 2020

colors = ["red", "green", "blue", "yellow", "black"]
for color in range(0,len(colors)):`
    print(color)       #This will print the index 
    
#refer below code if you want to print index with the value    
for color in range(0,len(colors)):
    print('Index value is '+str(color)+' and its value is '+str(colors[color]))


I think this is what you want to achieve

Answered by Code run on November 28, 2020

I think you were trying to write colors not color

You can Try this

colors = ["red", "green", "blue", "yellow", "black"]
map(print, colors)

It will do what you were trying to do

Answered by kiki7000 on November 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP