Search code examples
pythonjupyter-notebookpylint

Why are these lines of code legal in python?


Edit: It seems this question is confused with list slicing and wrong code being used. Clarified the question further.

I would like to ask what do the following 2 lines of code literally mean in python.

In [51]: data = list(range(10))                                                                              
In [53]: data[-1]   

Background

I accidentally ran the above raw Jupyter Notebook output through a python syntax checker (pylint) and surprisingly it did not throw out a syntax error, but instead

In [53]: data[-1]  
   ^ (bad-whitespace)
code2.py:1:0: C0111: Missing module docstring (missing-docstring)
code2.py:1:0: E0602: Undefined variable 'In' (undefined-variable)
code2.py:1:9: E0602: Undefined variable 'data' (undefined-variable)
code2.py:2:0: E0602: Undefined variable 'In' (undefined-variable)
code2.py:2:9: E0602: Undefined variable 'data' (undefined-variable)

------------------------------------------------------------------------
Your code has been rated at -115.00/10 (previous run: -90.00/10, -25.00)

So I tried understanding what those lines of code were literally doing.

And I tried plugging in the missing variables.

This Is where I got the following result that looks like a dictionary assignment.

In = {}
data = ['apple'] # This list needed values, otherwise data[-1] threw an error

In [51]: data = list(range(10))                                                                              
In [53]: data[-1] 

print(In)    # {51: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}

# Why were there no values for key 53? (either {53: 'apple'})

I could not really understand what is going on with the 2 lines of code.

I didn't think that this line of code was legal In [51]: data = list(range(10)) and since it was so, why did In [53] value not get assigned after that?

So any explanation or direction to references would be greatly appreciated. Thank you.


Solution

  • Will be answering this question in case anybody had the same questions as me.

    Thanks to @Goyo for pointing me towards Variable Annotations which was introduced in Python 3.6

    variable: annotation = assignment
    

    This syntax is used to annotate types in variables as compared to using comments (fruit: str = 'apple' vs fruit = 'apple' # type: str).

    The value in the annotation field is not strictly enforced and that was the reason why the syntax was legal.

    First statement

    In [51]: data = list(range(10))
    
    Variable = In [51] 
    Annotation = data
    Assignment = list(range(10))  
    

    Second statement

    In [53]: data[-1]
    
    Variable = In [53]
    Annotation = data[-1]