-1

I am trying to create a for loop to write multiple associated variables defined by the user to a database, is there a way to do something like this?

import sqlite3 as lite
import sys

names = ( "John", "Sal", "Bill" )
ids = ( 123, 321, 231 )

con = lite.connect('test.db')
cur = con.cursor()

**for x in names and y in id:**

  cur.execute("INSERT INTO People(Name, ID) VALUES('%s', %d)" % x y)
Eli Smith
  • 39
  • 1
  • 1
  • 5
  • 3
    This is such a common issue in python you should have googled for the answer before posting a question here. There are many such questions on the web. `zip` will solve your problem. – zephyr Dec 02 '15 at 21:29
  • 1
    Thanks for the help, for one, this question has proper spelling and grammar, and for two, I have searched through google but could not find help there. I'm sorry for posting a question to a question forum. – Eli Smith Dec 04 '15 at 15:09
  • 2
    @zephyr: Yet in google search for 'python multiple variable for loop' this appears first in the results. Thank you Eli Smith for this question. – Youda008 Apr 06 '17 at 13:42

1 Answers1

9

To iterate through multiple iterables at the same time, use zip.

>>> names = ( "John", "Sal", "Bill" )
>>> ids = ( 123, 321, 231 )
>>> for x,y in zip(names, ids):
...     print x,y
...
John 123
Sal 321
Bill 231
Kevin
  • 74,910
  • 12
  • 133
  • 166