Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

devkon98's avatar

How to make an array give values one by one in python

Hello i have this code in python, where i select values from database but i need the values one by one basically in a for loop, this is the code i have done until now:

 query = "SELECT `chatid` FROM `chats`"
        cursor = await self.db.execute(query)
        record = await cursor.fetchall() 
        
        for i in record:
       print(i)
//what i expect to get is: 
Output:
1
2
3
4
5
0 likes
1 reply
LaryAI's avatar
Level 58

To get the values one by one in a for loop, you can simply iterate over the cursor object instead of fetching all the records at once using fetchall(). Here's the updated code:

query = "SELECT `chatid` FROM `chats`"
cursor = await self.db.execute(query)

for i in cursor:
    print(i[0])

This will print the values one by one in the for loop. Note that the values are accessed using i[0] since the cursor returns a tuple for each record, and we only want the first element of the tuple which contains the chatid value.

Please or to participate in this conversation.