0

I came across a strange format of Python code about routine. What is the actual meaning?

def get_values() -> list:
    query = "select value from table"
    result = db.execute(query)
    return [ value[0] for value in result ]

I think the -> list means this routine returns data type list but I don't understand how the return (build a list)? Why it is value[0]?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • https://peps.python.org/pep-0484/ there you go. – Rinkesh P Apr 30 '22 at 15:47
  • ```return [ value[0] for value in result ]``` implies the variable result contains an iterable of lists/tuples from which you want to return the [0] element from each list/tuple in the iterable result. – itprorh66 Apr 30 '22 at 18:34
  • Do these answer your question? [What does "list comprehension" and similar mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-and-similar-mean-how-does-it-work-and-how-can-i), [What does -> mean in Python function definitions?](https://stackoverflow.com/questions/14379753/what-does-mean-in-python-function-definitions) – wjandrea Apr 30 '22 at 18:38

1 Answers1

0

If you are using sqlite3 (guessing) execute() returns a <sqlite3.Cursor> an iterable containing the tuples satisfying the conditions of your query.

Something like

('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
('2006-04-06', 'SELL', 'IBM', 500, 53.0)
('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
...

Then

[value[0] for value in result]

creates a list of all the first columns in result.

['2006-01-05', '2006-03-28', '2006-04-06', '2006-04-05', ...]
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134