I'm trying to get certain data in columns from my MySQL database but I get this error when trying to index a list in a for loop. Everything works well until I'm trying to print out data from 1 column.
Here's the list. I do believe this is a tuple but that shouldn't be the problem. (I think)
(1, 'Router', '192.168.1.1', '80')
Here's my code:
myresult = mycursor.fetchall()
for x in myresult:
print(x)
time.sleep(0.2)
ip = myresult[2]
print(ip)
This is the IndexError:
.....
File "directory..", line 172, in huvudmeny2
ip = myresult[2]
IndexError: list index out of range
Process finished with exit code 1
How can it be out of range when it has 4 items?
fetchall()returns a list of tuples not a single tuple. If you have only one result, that will be a list with one item (which will be the the tuple in question). Your ip is probably atx[2]for each result.myresult[2]is trying to get the third row of the results.fetchone()is a better choice here. Then you just get the tuple you are looking for and can index it the way you like.fetchall.