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
1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Nitpick: zip is a built-in function, not a keyword.
@WillemVanOnsem , Thanks, fixed that.
Thank you @omri_saadon. I am now able to insert multiple values in the database. I thought zip can only be used to zip two list and transform them into dictionary. Never thought zip can work in this way.
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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.