Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print a variable within an array using its index

I am practicing with for in loops and having trouble with this.

places = ["phuket", "athens", "doha"]

for places in range(5):
    if places == 0:
        print("thailand," + places 0 + "is a cool place")
    else:
        print("not thailand")

When I try this, I get a syntax error with ‘places 0’. I want it to print thailand, phuket, is a cool place. But no matter how I seem to format places 0 (with the 0 in [], with it in ()) I just keep getting syntax errors.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you use enumerate you can get the index of the for loop.
i will be 0, 1, 2 and place will be phuket, athens, doha.
And you can use different logic depends on what you want.

places = ["phuket", "athens", "doha"]

for i,place in enumerate(places):
    if i == 0:
        print("thailand," + place + "is a cool place")
    else:
        print("not thailand")

You can understand more here – https://realpython.com/python-enumerate/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading