0

I have the following code in Python and I am an unsure about how the for loop here is working.

cur.execute("SELECT CUST_ID, COMPANY, LASTNAME, CITY, STATE FROM 
mytable")                            

colnames = [desc[0] for desc in cur.description]      

How does this for work ?

[desc[0] for desc in cur.description]   

What is desc[0]?

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
AJAY
  • 73
  • 5

3 Answers3

5

Based on the code you've given us it seems like desc is an array itself and thus colnames is an array of all the desc[0] you get from each desc in cur.description

desc[0] is the first item in desc as arrays in Python are zero-indexed.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
Haardik
  • 187
  • 1
  • 13
  • conn = db2.connect() cur = conn.cursor() cur.execute("SELECT CUST_ID, COMPANY, LASTNAME, CITY, STATE FROM \ zendphp7.sp_cust WHERE COUNTRY = 'US'") colnames = [desc[0] for desc in cur.description] – AJAY Mar 24 '18 at 03:47
  • cur.description is a LIST , and looks like Colnames is also list – AJAY Mar 24 '18 at 03:47
  • You should put code edits in the main post. Regardless, your question has been answered. – Haardik Mar 24 '18 at 03:47
  • Yes, and I have explained why it's a list above. – Haardik Mar 24 '18 at 03:48
1

It use iterable objects especially next methode it will consume the value inside the objects till get stop iteration, it works like a generator objects....

Wira Bhakti
  • 388
  • 3
  • 14
1

When in doubt of something, try to recreate the thing. Althought, it could be anything iterable, we could assume it's just a list, then:

description = [['first'], ['second', 'third'], [x, y, z], [...], ...]
colnames = [desc[0] for desc in description]

in the output you'll have: ['first', 'second', x, ... ]

R.R.C.
  • 5,439
  • 3
  • 14
  • 19
  • why are we not getting "third" ? – AJAY Mar 24 '18 at 03:58
  • @AJAY, `second` and `third` is in the same list, since we doing `desc[0]`, we getting `second`, that is, the first element. Notice that it is lists inside a list. `[ ['first'], ['second', 'third'], [...], ... ]` – R.R.C. Mar 24 '18 at 04:02
  • Got it thanks, where can i find a good explanation on list in python – AJAY Mar 24 '18 at 04:10
  • @AJAY, that's hard to tell, but typing python lists in google search will give you a huge number of websites that you can dig in. Here's some: Python Documentation for data structure => https://docs.python.org/3/tutorial/datastructures.html and here's a random => https://www.programiz.com/python-programming/list Try them. – R.R.C. Mar 24 '18 at 04:15