0

Python allows me to make the following statement...

records = list()

ie declare a name/variable that is at present of type 'List'

The following syntax does not throw a syntax error but I'm not sure what it actually does...

records: list()

Any ideas when you might use the colon version? Why is it syntactically correct if when I query its type I get an error?

records = list()
print(type(records)

>> <class 'list'>

records: list()
print(type(records)

>> NameError: name 'records' is not defined
  • It's a type hint that says that when you assign to the variable you'll give it a value whose type is whatever `list()` returns. – Barmar Feb 15 '23 at 16:38
  • Note that it should be `records: list` without the `()`. – Barmar Feb 15 '23 at 16:38
  • Great thanks Barmar - fully understood - apart from a quick follow-up, why not the parentheses? – templegate Feb 15 '23 at 16:41
  • @templegate `list` is a type, `list()` is an expression that happens to evaluate to a list object. Type checkers won't understand the latter – Brian61354270 Feb 15 '23 at 16:42
  • `records = list()` doesn't declare the type of the variable. It calls the function `list()`, which returns a list, and assigns that value to the variable. Nothing stops you from doing `records = 3` after that. – Barmar Feb 15 '23 at 16:43

0 Answers0