Home > front end >  How to access a lists text value from inside a loop using range in Python
How to access a lists text value from inside a loop using range in Python

Time:09-27

I have a loop with range but I need to access the text value from inside the loop. I can use a loop without range but I also need the range value.

list = ["red", "yellow". "green"]

for i in range (0, len(list)): # 3 (0-2)
    print(i) # 1, 2, 3

for i in list
    print(i) # red, yellow, green
    

How could I do something like the below

for i in range (0, len(list)):
    print(i) # 1, 2, 3
    print(i.text/value???) # red, yellow, green

CodePudding user response:

Using enumerate would be a better idea for this.

lst = ["red", "yellow". "green"]
for index, value in enumerate(lst):
    print(index) # 1, 2, 3
    print(value) # red, yellow, green

CodePudding user response:

You can just use i as an index of list. Like this:

lst = ["red", "yellow", "green"]
for i in range (0, len(lst)):
    print(i) # 1, 2, 3
    print(lst[i]) # red, yellow, green

Notice that I renamed list to lst. This is because list is a reserved keyword in Python and you cannot use it as a variable name. If you try to do so, then you will run into problems.

  • Related