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

I can't print a specific set in a list in python

coordinates=[(4,5),(5,6,(6,6))]
print(coordinates[3])

result:Traceback (most recent call last):
  File "C:\Users\PycharmProjects\pythonProject1\App.py", line 2, in <module>
    print(coordinates[3])
IndexError: list index out of range

I want the result to be [6,6] instead of the error message what do you mean i am trying to access a fourth one I am trying to access the 3rd one in the list when i use coordinates[1][2] it gives me a syntax error

>Solution :

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

There are 2 problems:

(1) Items in a list are zero-indexed, meaning the first element of L is L[0], second is L[1], etc. So if you want the third item:

print(coordinates[2])

(2) If you just stop there, you’ll still get an index out of range exception, because your list has only 2 elements. I think you’ve misplaced a ):

coordinates=[(4,5),(5,6),(6,6)]

In your question, your list coordinates has 2 elements: (4, 5) and (5, 6, (6, 6)) – notice the nested parentheses. The second item is the set containing 3 elements: 5, 6, and another set (6,6).

Tip: Sometimes I like to put lists on multiple lines, especially if they are nested or contain sets/tuples/other complicated structures. One widely accepted style for this is shown below:

coordinates = [
    (4,5)
    (5,6)
    (6,6)
]
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