AnswerBun.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!

Related Questions

Find a cell containing a specific date

1  Asked on December 22, 2021

       

Jeykll file to import not found or unreadable: base

1  Asked on December 22, 2021 by kyu96

       

Unable to remove event listener from document

1  Asked on December 22, 2021 by prawn

     

Invalid result adding the number of 1s in a binary number

2  Asked on December 20, 2021 by aworeham

   

How to print the elements of 3 different arrays by the order?

2  Asked on December 20, 2021 by fuzzyfiso

 

Finding string elements of an array in another array

5  Asked on December 20, 2021 by p-emt

     

How to plot several columns on the same line chart in R?

2  Asked on December 20, 2021 by user13953317

     

Is there a way to craft URLs to fill forms faster?

1  Asked on December 20, 2021 by rosalind-goh

   

infinite loop while using useEffect and redux store

0  Asked on December 20, 2021 by susanta

     

Cannot convert textfield into string

1  Asked on December 20, 2021 by anuj-amin

       

Is there multiple ways to cin vector elements?

1  Asked on December 20, 2021 by 2kbummer

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir