0

I have three list and basically i want handle of storing their values in one go within the for loop. Below is what i am trying to accomplish

a = ['abc', 'efg']
b = ['hij', 'klm']
c = ['nop', 'qrs']

for i, g, t in a, b, c:
    Insert into database %i and %j and %c
fear_matrix
  • 4,912
  • 10
  • 44
  • 65
  • 1
    Possible duplicate of [How can I iterate through two lists in parallel in Python?](http://stackoverflow.com/questions/1663807/how-can-i-iterate-through-two-lists-in-parallel-in-python) – juanpa.arrivillaga Feb 20 '17 at 10:14

2 Answers2

5

You can use the zip built-in function:

for i, g, t in zip(a, b, c):
    Insert into database %i and %g and %t

zip([iterable, ...])

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables

You can read the docs for more information

Note: If your lists are not equally (by length) you can use the izip_longest from itertools lib.

itertools.izip_longest(*iterables[, fillvalue]) Make an iterator that

aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.

For more info about izip_longest, read here

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
0

Another solution which is perhaps less clean compared to the zip answer provided elsewhere is to:

a=[1,2,3]
b=[4,5,6]
for i in range(len(a)):
    insert_into_database(a[i],b[i])

would also work but is less clean/elegant :)

Henry
  • 1,646
  • 12
  • 28