How to iterate through two lists in parallel?












655















I have two iterables in Python, and I want to go over them in pairs:



foo = (1, 2, 3)
bar = (4, 5, 6)

for (f, b) in some_iterator(foo, bar):
print "f: ", f, "; b: ", b


It should result in:



f: 1; b: 4
f: 2; b: 5
f: 3; b: 6


One way to do it is to iterate over the indices:



for i in xrange(len(foo)):
print "f: ", foo[i], "; b: ", b[i]


But that seems somewhat unpythonic to me. Is there a better way to do it?










share|improve this question





























    655















    I have two iterables in Python, and I want to go over them in pairs:



    foo = (1, 2, 3)
    bar = (4, 5, 6)

    for (f, b) in some_iterator(foo, bar):
    print "f: ", f, "; b: ", b


    It should result in:



    f: 1; b: 4
    f: 2; b: 5
    f: 3; b: 6


    One way to do it is to iterate over the indices:



    for i in xrange(len(foo)):
    print "f: ", foo[i], "; b: ", b[i]


    But that seems somewhat unpythonic to me. Is there a better way to do it?










    share|improve this question



























      655












      655








      655


      202






      I have two iterables in Python, and I want to go over them in pairs:



      foo = (1, 2, 3)
      bar = (4, 5, 6)

      for (f, b) in some_iterator(foo, bar):
      print "f: ", f, "; b: ", b


      It should result in:



      f: 1; b: 4
      f: 2; b: 5
      f: 3; b: 6


      One way to do it is to iterate over the indices:



      for i in xrange(len(foo)):
      print "f: ", foo[i], "; b: ", b[i]


      But that seems somewhat unpythonic to me. Is there a better way to do it?










      share|improve this question
















      I have two iterables in Python, and I want to go over them in pairs:



      foo = (1, 2, 3)
      bar = (4, 5, 6)

      for (f, b) in some_iterator(foo, bar):
      print "f: ", f, "; b: ", b


      It should result in:



      f: 1; b: 4
      f: 2; b: 5
      f: 3; b: 6


      One way to do it is to iterate over the indices:



      for i in xrange(len(foo)):
      print "f: ", foo[i], "; b: ", b[i]


      But that seems somewhat unpythonic to me. Is there a better way to do it?







      python iterator






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 30 '17 at 20:24









      martineau

      68.9k1091186




      68.9k1091186










      asked Nov 2 '09 at 21:26









      Nathan FellmanNathan Fellman

      61.9k80225292




      61.9k80225292
























          8 Answers
          8






          active

          oldest

          votes


















          1034














          for f, b in zip(foo, bar):
          print(f, b)


          zip stops when the shorter of foo or bar stops.



          In Python 2, zip
          returns a list of tuples. This is fine when foo and bar are not massive. If
          they are both massive then forming zip(foo,bar) is an unnecessarily massive
          temporary variable, and should be replaced by itertools.izip or
          itertools.izip_longest, which returns an iterator instead of a list.



          import itertools
          for f,b in itertools.izip(foo,bar):
          print(f,b)
          for f,b in itertools.izip_longest(foo,bar):
          print(f,b)


          izip stops when either foo or bar is exhausted.
          izip_longest stops when both foo and bar are exhausted.
          When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.



          In Python 3, zip
          returns an iterator of tuples, like itertools.izip in Python2. To get a list
          of tuples, use list(zip(foo, bar)). And to zip until both iterators are
          exhausted, you would use
          itertools.zip_longest.





          Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,



          for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
          ['red', 'blue', 'green']):
          print('{} {} {}'.format(num, color, cheese))


          prints



          1 red manchego
          2 blue stilton
          3 green brie





          share|improve this answer





















          • 3





            @unutbu In Python 3, the function name is itertools.zip_longest, instead of itertools.izip_longest (basically zip... instead of izip... in the itertools module). It's a one character edit, otherwise I'd edit the super minor correction into your answer myself.

            – Michael A
            Oct 15 '14 at 20:04













          • @unutbu Why would I prefer OP's method over the izip one (even though the izip/ zip looks much cleaner)?

            – armundle
            Mar 14 '16 at 19:23






          • 2





            You might want to mention Python 3 first, as it's probably more future-proof. Moreover, it*s worth pointing out that in Python 3, zip() has exactly that advantage that only itertools.izip() had in Python 2 and thus it is usually the way to go.

            – Daniel S.
            Jun 14 '16 at 17:40






          • 2





            May I ask you to update your answer to explicitly state that zip and zip-like functions from itertools accept any number of iterables and not just 2? This question is canonical now and your answer is the only one worth updating.

            – vaultah
            Jul 11 '16 at 15:01






          • 1





            @CharlieParker: Yes you can, but then you would use for i, (f, b) in enumerate(zip(foo, bar)).

            – unutbu
            Mar 6 '18 at 19:20



















          46














          You want the zip function.



          for (f,b) in zip(foo, bar):
          print "f: ", f ,"; b: ", b





          share|improve this answer



















          • 10





            Before Python 3.0 you'd want to use itertools.izip if you have large numbers of elements.

            – Georg Schölly
            Nov 2 '09 at 21:35



















          14














          The builtin zip does exactly what you want. If you want the same over iterables instead of lists you could look at itertools.izip which does the same thing but gives results one at a time.






          share|improve this answer































            11














            What you're looking for is called zip.






            share|improve this answer































              6














              You should use 'zip' function. Here is an example how your own zip function can look like



              def custom_zip(seq1, seq2):
              it1 = iter(seq1)
              it2 = iter(seq2)
              while True:
              yield next(it1), next(it2)





              share|improve this answer
























              • Doesn't this have exactly the same result as zip(seq1, seq2)?

                – Niklas Mertsch
                Jun 6 '18 at 9:35











              • @NiklasMertsch yes it has exactly the same result. I just provided example how zip function looks like

                – Vlad Bezden
                Jun 6 '18 at 15:40



















              5














              zip function solves the issue

              Docs: ZIP Library function



              AIM: To put the output side by side
              Problem:



              #value1 is a list
              value1 = driver.find_elements_by_class_name("review-text")
              #value2 is a list
              value2 = driver.find_elements_by_class_name("review-date")

              for val1 in value1:
              print(val1.text)
              print "n"
              for val2 in value2:
              print(val2.text)
              print "n"


              Output:

              review1

              review2

              review3

              date1

              date2

              date3



              Solution:



              for val1, val2 in zip(value1,value2):
              print (val1.text+':'+val2.text)
              print "n"


              Output:

              review1:date1

              review2:date2

              review3:date3






              share|improve this answer































                0














                you can use 3 type in one dictionary :



                def construct_dictionary_from_lists(names, ages, scores):
                end_str_dic = {}
                for item_name, item_age, score_item in zip(names, ages, scores):
                end_str_dic[item_name] = item_age, score_item
                return end_str_dic


                print(
                construct_dictionary_from_lists(
                ["paul", "saul", "steve", "chimpy"],
                [28, 59, 22, 5],
                [59, 85, 55, 60]
                )
                )





                share|improve this answer

































                  -4














                  def ncustom_zip(seq1,seq2,max_length):
                  length= len(seq1) if len(seq1)>len(seq2) else len(seq2) if max_length else len(seq1) if len(seq1)<len(seq2) else len(seq2)
                  for i in range(length):
                  x= seq1[i] if len(seq1)>i else None
                  y= seq2[i] if len(seq2)>i else None
                  yield x,y


                  l=[12,2,3,9]
                  p=[89,8,92,5,7]

                  for i,j in ncustom_zip(l,p,True):
                  print i,j
                  for i,j in ncustom_zip(l,p,False):
                  print i,j





                  share|improve this answer


























                  • is this my answer is right?

                    – Sagar T
                    Dec 24 '17 at 14:09











                  • what is wrong in my answer.?

                    – Sagar T
                    Dec 25 '17 at 5:12






                  • 6





                    As explained in the first comment, it is lacking explanation what your code is doing, why it is better/different from the other options, what its performance and memory implication are etc. Just a code dump is not a good answer on Stack Overflow

                    – rene
                    Dec 25 '17 at 10:41











                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1663807%2fhow-to-iterate-through-two-lists-in-parallel%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  8 Answers
                  8






                  active

                  oldest

                  votes








                  8 Answers
                  8






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  1034














                  for f, b in zip(foo, bar):
                  print(f, b)


                  zip stops when the shorter of foo or bar stops.



                  In Python 2, zip
                  returns a list of tuples. This is fine when foo and bar are not massive. If
                  they are both massive then forming zip(foo,bar) is an unnecessarily massive
                  temporary variable, and should be replaced by itertools.izip or
                  itertools.izip_longest, which returns an iterator instead of a list.



                  import itertools
                  for f,b in itertools.izip(foo,bar):
                  print(f,b)
                  for f,b in itertools.izip_longest(foo,bar):
                  print(f,b)


                  izip stops when either foo or bar is exhausted.
                  izip_longest stops when both foo and bar are exhausted.
                  When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.



                  In Python 3, zip
                  returns an iterator of tuples, like itertools.izip in Python2. To get a list
                  of tuples, use list(zip(foo, bar)). And to zip until both iterators are
                  exhausted, you would use
                  itertools.zip_longest.





                  Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,



                  for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
                  ['red', 'blue', 'green']):
                  print('{} {} {}'.format(num, color, cheese))


                  prints



                  1 red manchego
                  2 blue stilton
                  3 green brie





                  share|improve this answer





















                  • 3





                    @unutbu In Python 3, the function name is itertools.zip_longest, instead of itertools.izip_longest (basically zip... instead of izip... in the itertools module). It's a one character edit, otherwise I'd edit the super minor correction into your answer myself.

                    – Michael A
                    Oct 15 '14 at 20:04













                  • @unutbu Why would I prefer OP's method over the izip one (even though the izip/ zip looks much cleaner)?

                    – armundle
                    Mar 14 '16 at 19:23






                  • 2





                    You might want to mention Python 3 first, as it's probably more future-proof. Moreover, it*s worth pointing out that in Python 3, zip() has exactly that advantage that only itertools.izip() had in Python 2 and thus it is usually the way to go.

                    – Daniel S.
                    Jun 14 '16 at 17:40






                  • 2





                    May I ask you to update your answer to explicitly state that zip and zip-like functions from itertools accept any number of iterables and not just 2? This question is canonical now and your answer is the only one worth updating.

                    – vaultah
                    Jul 11 '16 at 15:01






                  • 1





                    @CharlieParker: Yes you can, but then you would use for i, (f, b) in enumerate(zip(foo, bar)).

                    – unutbu
                    Mar 6 '18 at 19:20
















                  1034














                  for f, b in zip(foo, bar):
                  print(f, b)


                  zip stops when the shorter of foo or bar stops.



                  In Python 2, zip
                  returns a list of tuples. This is fine when foo and bar are not massive. If
                  they are both massive then forming zip(foo,bar) is an unnecessarily massive
                  temporary variable, and should be replaced by itertools.izip or
                  itertools.izip_longest, which returns an iterator instead of a list.



                  import itertools
                  for f,b in itertools.izip(foo,bar):
                  print(f,b)
                  for f,b in itertools.izip_longest(foo,bar):
                  print(f,b)


                  izip stops when either foo or bar is exhausted.
                  izip_longest stops when both foo and bar are exhausted.
                  When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.



                  In Python 3, zip
                  returns an iterator of tuples, like itertools.izip in Python2. To get a list
                  of tuples, use list(zip(foo, bar)). And to zip until both iterators are
                  exhausted, you would use
                  itertools.zip_longest.





                  Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,



                  for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
                  ['red', 'blue', 'green']):
                  print('{} {} {}'.format(num, color, cheese))


                  prints



                  1 red manchego
                  2 blue stilton
                  3 green brie





                  share|improve this answer





















                  • 3





                    @unutbu In Python 3, the function name is itertools.zip_longest, instead of itertools.izip_longest (basically zip... instead of izip... in the itertools module). It's a one character edit, otherwise I'd edit the super minor correction into your answer myself.

                    – Michael A
                    Oct 15 '14 at 20:04













                  • @unutbu Why would I prefer OP's method over the izip one (even though the izip/ zip looks much cleaner)?

                    – armundle
                    Mar 14 '16 at 19:23






                  • 2





                    You might want to mention Python 3 first, as it's probably more future-proof. Moreover, it*s worth pointing out that in Python 3, zip() has exactly that advantage that only itertools.izip() had in Python 2 and thus it is usually the way to go.

                    – Daniel S.
                    Jun 14 '16 at 17:40






                  • 2





                    May I ask you to update your answer to explicitly state that zip and zip-like functions from itertools accept any number of iterables and not just 2? This question is canonical now and your answer is the only one worth updating.

                    – vaultah
                    Jul 11 '16 at 15:01






                  • 1





                    @CharlieParker: Yes you can, but then you would use for i, (f, b) in enumerate(zip(foo, bar)).

                    – unutbu
                    Mar 6 '18 at 19:20














                  1034












                  1034








                  1034







                  for f, b in zip(foo, bar):
                  print(f, b)


                  zip stops when the shorter of foo or bar stops.



                  In Python 2, zip
                  returns a list of tuples. This is fine when foo and bar are not massive. If
                  they are both massive then forming zip(foo,bar) is an unnecessarily massive
                  temporary variable, and should be replaced by itertools.izip or
                  itertools.izip_longest, which returns an iterator instead of a list.



                  import itertools
                  for f,b in itertools.izip(foo,bar):
                  print(f,b)
                  for f,b in itertools.izip_longest(foo,bar):
                  print(f,b)


                  izip stops when either foo or bar is exhausted.
                  izip_longest stops when both foo and bar are exhausted.
                  When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.



                  In Python 3, zip
                  returns an iterator of tuples, like itertools.izip in Python2. To get a list
                  of tuples, use list(zip(foo, bar)). And to zip until both iterators are
                  exhausted, you would use
                  itertools.zip_longest.





                  Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,



                  for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
                  ['red', 'blue', 'green']):
                  print('{} {} {}'.format(num, color, cheese))


                  prints



                  1 red manchego
                  2 blue stilton
                  3 green brie





                  share|improve this answer















                  for f, b in zip(foo, bar):
                  print(f, b)


                  zip stops when the shorter of foo or bar stops.



                  In Python 2, zip
                  returns a list of tuples. This is fine when foo and bar are not massive. If
                  they are both massive then forming zip(foo,bar) is an unnecessarily massive
                  temporary variable, and should be replaced by itertools.izip or
                  itertools.izip_longest, which returns an iterator instead of a list.



                  import itertools
                  for f,b in itertools.izip(foo,bar):
                  print(f,b)
                  for f,b in itertools.izip_longest(foo,bar):
                  print(f,b)


                  izip stops when either foo or bar is exhausted.
                  izip_longest stops when both foo and bar are exhausted.
                  When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.



                  In Python 3, zip
                  returns an iterator of tuples, like itertools.izip in Python2. To get a list
                  of tuples, use list(zip(foo, bar)). And to zip until both iterators are
                  exhausted, you would use
                  itertools.zip_longest.





                  Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,



                  for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
                  ['red', 'blue', 'green']):
                  print('{} {} {}'.format(num, color, cheese))


                  prints



                  1 red manchego
                  2 blue stilton
                  3 green brie






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 11 '16 at 17:13

























                  answered Nov 2 '09 at 21:28









                  unutbuunutbu

                  557k10511961253




                  557k10511961253








                  • 3





                    @unutbu In Python 3, the function name is itertools.zip_longest, instead of itertools.izip_longest (basically zip... instead of izip... in the itertools module). It's a one character edit, otherwise I'd edit the super minor correction into your answer myself.

                    – Michael A
                    Oct 15 '14 at 20:04













                  • @unutbu Why would I prefer OP's method over the izip one (even though the izip/ zip looks much cleaner)?

                    – armundle
                    Mar 14 '16 at 19:23






                  • 2





                    You might want to mention Python 3 first, as it's probably more future-proof. Moreover, it*s worth pointing out that in Python 3, zip() has exactly that advantage that only itertools.izip() had in Python 2 and thus it is usually the way to go.

                    – Daniel S.
                    Jun 14 '16 at 17:40






                  • 2





                    May I ask you to update your answer to explicitly state that zip and zip-like functions from itertools accept any number of iterables and not just 2? This question is canonical now and your answer is the only one worth updating.

                    – vaultah
                    Jul 11 '16 at 15:01






                  • 1





                    @CharlieParker: Yes you can, but then you would use for i, (f, b) in enumerate(zip(foo, bar)).

                    – unutbu
                    Mar 6 '18 at 19:20














                  • 3





                    @unutbu In Python 3, the function name is itertools.zip_longest, instead of itertools.izip_longest (basically zip... instead of izip... in the itertools module). It's a one character edit, otherwise I'd edit the super minor correction into your answer myself.

                    – Michael A
                    Oct 15 '14 at 20:04













                  • @unutbu Why would I prefer OP's method over the izip one (even though the izip/ zip looks much cleaner)?

                    – armundle
                    Mar 14 '16 at 19:23






                  • 2





                    You might want to mention Python 3 first, as it's probably more future-proof. Moreover, it*s worth pointing out that in Python 3, zip() has exactly that advantage that only itertools.izip() had in Python 2 and thus it is usually the way to go.

                    – Daniel S.
                    Jun 14 '16 at 17:40






                  • 2





                    May I ask you to update your answer to explicitly state that zip and zip-like functions from itertools accept any number of iterables and not just 2? This question is canonical now and your answer is the only one worth updating.

                    – vaultah
                    Jul 11 '16 at 15:01






                  • 1





                    @CharlieParker: Yes you can, but then you would use for i, (f, b) in enumerate(zip(foo, bar)).

                    – unutbu
                    Mar 6 '18 at 19:20








                  3




                  3





                  @unutbu In Python 3, the function name is itertools.zip_longest, instead of itertools.izip_longest (basically zip... instead of izip... in the itertools module). It's a one character edit, otherwise I'd edit the super minor correction into your answer myself.

                  – Michael A
                  Oct 15 '14 at 20:04







                  @unutbu In Python 3, the function name is itertools.zip_longest, instead of itertools.izip_longest (basically zip... instead of izip... in the itertools module). It's a one character edit, otherwise I'd edit the super minor correction into your answer myself.

                  – Michael A
                  Oct 15 '14 at 20:04















                  @unutbu Why would I prefer OP's method over the izip one (even though the izip/ zip looks much cleaner)?

                  – armundle
                  Mar 14 '16 at 19:23





                  @unutbu Why would I prefer OP's method over the izip one (even though the izip/ zip looks much cleaner)?

                  – armundle
                  Mar 14 '16 at 19:23




                  2




                  2





                  You might want to mention Python 3 first, as it's probably more future-proof. Moreover, it*s worth pointing out that in Python 3, zip() has exactly that advantage that only itertools.izip() had in Python 2 and thus it is usually the way to go.

                  – Daniel S.
                  Jun 14 '16 at 17:40





                  You might want to mention Python 3 first, as it's probably more future-proof. Moreover, it*s worth pointing out that in Python 3, zip() has exactly that advantage that only itertools.izip() had in Python 2 and thus it is usually the way to go.

                  – Daniel S.
                  Jun 14 '16 at 17:40




                  2




                  2





                  May I ask you to update your answer to explicitly state that zip and zip-like functions from itertools accept any number of iterables and not just 2? This question is canonical now and your answer is the only one worth updating.

                  – vaultah
                  Jul 11 '16 at 15:01





                  May I ask you to update your answer to explicitly state that zip and zip-like functions from itertools accept any number of iterables and not just 2? This question is canonical now and your answer is the only one worth updating.

                  – vaultah
                  Jul 11 '16 at 15:01




                  1




                  1





                  @CharlieParker: Yes you can, but then you would use for i, (f, b) in enumerate(zip(foo, bar)).

                  – unutbu
                  Mar 6 '18 at 19:20





                  @CharlieParker: Yes you can, but then you would use for i, (f, b) in enumerate(zip(foo, bar)).

                  – unutbu
                  Mar 6 '18 at 19:20













                  46














                  You want the zip function.



                  for (f,b) in zip(foo, bar):
                  print "f: ", f ,"; b: ", b





                  share|improve this answer



















                  • 10





                    Before Python 3.0 you'd want to use itertools.izip if you have large numbers of elements.

                    – Georg Schölly
                    Nov 2 '09 at 21:35
















                  46














                  You want the zip function.



                  for (f,b) in zip(foo, bar):
                  print "f: ", f ,"; b: ", b





                  share|improve this answer



















                  • 10





                    Before Python 3.0 you'd want to use itertools.izip if you have large numbers of elements.

                    – Georg Schölly
                    Nov 2 '09 at 21:35














                  46












                  46








                  46







                  You want the zip function.



                  for (f,b) in zip(foo, bar):
                  print "f: ", f ,"; b: ", b





                  share|improve this answer













                  You want the zip function.



                  for (f,b) in zip(foo, bar):
                  print "f: ", f ,"; b: ", b






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 2 '09 at 21:27









                  Karl GuertinKarl Guertin

                  3,07721719




                  3,07721719








                  • 10





                    Before Python 3.0 you'd want to use itertools.izip if you have large numbers of elements.

                    – Georg Schölly
                    Nov 2 '09 at 21:35














                  • 10





                    Before Python 3.0 you'd want to use itertools.izip if you have large numbers of elements.

                    – Georg Schölly
                    Nov 2 '09 at 21:35








                  10




                  10





                  Before Python 3.0 you'd want to use itertools.izip if you have large numbers of elements.

                  – Georg Schölly
                  Nov 2 '09 at 21:35





                  Before Python 3.0 you'd want to use itertools.izip if you have large numbers of elements.

                  – Georg Schölly
                  Nov 2 '09 at 21:35











                  14














                  The builtin zip does exactly what you want. If you want the same over iterables instead of lists you could look at itertools.izip which does the same thing but gives results one at a time.






                  share|improve this answer




























                    14














                    The builtin zip does exactly what you want. If you want the same over iterables instead of lists you could look at itertools.izip which does the same thing but gives results one at a time.






                    share|improve this answer


























                      14












                      14








                      14







                      The builtin zip does exactly what you want. If you want the same over iterables instead of lists you could look at itertools.izip which does the same thing but gives results one at a time.






                      share|improve this answer













                      The builtin zip does exactly what you want. If you want the same over iterables instead of lists you could look at itertools.izip which does the same thing but gives results one at a time.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 2 '09 at 21:28









                      robincerobince

                      9,32522542




                      9,32522542























                          11














                          What you're looking for is called zip.






                          share|improve this answer




























                            11














                            What you're looking for is called zip.






                            share|improve this answer


























                              11












                              11








                              11







                              What you're looking for is called zip.






                              share|improve this answer













                              What you're looking for is called zip.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 2 '09 at 21:28









                              Alex MartelliAlex Martelli

                              630k12810421284




                              630k12810421284























                                  6














                                  You should use 'zip' function. Here is an example how your own zip function can look like



                                  def custom_zip(seq1, seq2):
                                  it1 = iter(seq1)
                                  it2 = iter(seq2)
                                  while True:
                                  yield next(it1), next(it2)





                                  share|improve this answer
























                                  • Doesn't this have exactly the same result as zip(seq1, seq2)?

                                    – Niklas Mertsch
                                    Jun 6 '18 at 9:35











                                  • @NiklasMertsch yes it has exactly the same result. I just provided example how zip function looks like

                                    – Vlad Bezden
                                    Jun 6 '18 at 15:40
















                                  6














                                  You should use 'zip' function. Here is an example how your own zip function can look like



                                  def custom_zip(seq1, seq2):
                                  it1 = iter(seq1)
                                  it2 = iter(seq2)
                                  while True:
                                  yield next(it1), next(it2)





                                  share|improve this answer
























                                  • Doesn't this have exactly the same result as zip(seq1, seq2)?

                                    – Niklas Mertsch
                                    Jun 6 '18 at 9:35











                                  • @NiklasMertsch yes it has exactly the same result. I just provided example how zip function looks like

                                    – Vlad Bezden
                                    Jun 6 '18 at 15:40














                                  6












                                  6








                                  6







                                  You should use 'zip' function. Here is an example how your own zip function can look like



                                  def custom_zip(seq1, seq2):
                                  it1 = iter(seq1)
                                  it2 = iter(seq2)
                                  while True:
                                  yield next(it1), next(it2)





                                  share|improve this answer













                                  You should use 'zip' function. Here is an example how your own zip function can look like



                                  def custom_zip(seq1, seq2):
                                  it1 = iter(seq1)
                                  it2 = iter(seq2)
                                  while True:
                                  yield next(it1), next(it2)






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Apr 23 '17 at 11:09









                                  Vlad BezdenVlad Bezden

                                  30.4k10134115




                                  30.4k10134115













                                  • Doesn't this have exactly the same result as zip(seq1, seq2)?

                                    – Niklas Mertsch
                                    Jun 6 '18 at 9:35











                                  • @NiklasMertsch yes it has exactly the same result. I just provided example how zip function looks like

                                    – Vlad Bezden
                                    Jun 6 '18 at 15:40



















                                  • Doesn't this have exactly the same result as zip(seq1, seq2)?

                                    – Niklas Mertsch
                                    Jun 6 '18 at 9:35











                                  • @NiklasMertsch yes it has exactly the same result. I just provided example how zip function looks like

                                    – Vlad Bezden
                                    Jun 6 '18 at 15:40

















                                  Doesn't this have exactly the same result as zip(seq1, seq2)?

                                  – Niklas Mertsch
                                  Jun 6 '18 at 9:35





                                  Doesn't this have exactly the same result as zip(seq1, seq2)?

                                  – Niklas Mertsch
                                  Jun 6 '18 at 9:35













                                  @NiklasMertsch yes it has exactly the same result. I just provided example how zip function looks like

                                  – Vlad Bezden
                                  Jun 6 '18 at 15:40





                                  @NiklasMertsch yes it has exactly the same result. I just provided example how zip function looks like

                                  – Vlad Bezden
                                  Jun 6 '18 at 15:40











                                  5














                                  zip function solves the issue

                                  Docs: ZIP Library function



                                  AIM: To put the output side by side
                                  Problem:



                                  #value1 is a list
                                  value1 = driver.find_elements_by_class_name("review-text")
                                  #value2 is a list
                                  value2 = driver.find_elements_by_class_name("review-date")

                                  for val1 in value1:
                                  print(val1.text)
                                  print "n"
                                  for val2 in value2:
                                  print(val2.text)
                                  print "n"


                                  Output:

                                  review1

                                  review2

                                  review3

                                  date1

                                  date2

                                  date3



                                  Solution:



                                  for val1, val2 in zip(value1,value2):
                                  print (val1.text+':'+val2.text)
                                  print "n"


                                  Output:

                                  review1:date1

                                  review2:date2

                                  review3:date3






                                  share|improve this answer




























                                    5














                                    zip function solves the issue

                                    Docs: ZIP Library function



                                    AIM: To put the output side by side
                                    Problem:



                                    #value1 is a list
                                    value1 = driver.find_elements_by_class_name("review-text")
                                    #value2 is a list
                                    value2 = driver.find_elements_by_class_name("review-date")

                                    for val1 in value1:
                                    print(val1.text)
                                    print "n"
                                    for val2 in value2:
                                    print(val2.text)
                                    print "n"


                                    Output:

                                    review1

                                    review2

                                    review3

                                    date1

                                    date2

                                    date3



                                    Solution:



                                    for val1, val2 in zip(value1,value2):
                                    print (val1.text+':'+val2.text)
                                    print "n"


                                    Output:

                                    review1:date1

                                    review2:date2

                                    review3:date3






                                    share|improve this answer


























                                      5












                                      5








                                      5







                                      zip function solves the issue

                                      Docs: ZIP Library function



                                      AIM: To put the output side by side
                                      Problem:



                                      #value1 is a list
                                      value1 = driver.find_elements_by_class_name("review-text")
                                      #value2 is a list
                                      value2 = driver.find_elements_by_class_name("review-date")

                                      for val1 in value1:
                                      print(val1.text)
                                      print "n"
                                      for val2 in value2:
                                      print(val2.text)
                                      print "n"


                                      Output:

                                      review1

                                      review2

                                      review3

                                      date1

                                      date2

                                      date3



                                      Solution:



                                      for val1, val2 in zip(value1,value2):
                                      print (val1.text+':'+val2.text)
                                      print "n"


                                      Output:

                                      review1:date1

                                      review2:date2

                                      review3:date3






                                      share|improve this answer













                                      zip function solves the issue

                                      Docs: ZIP Library function



                                      AIM: To put the output side by side
                                      Problem:



                                      #value1 is a list
                                      value1 = driver.find_elements_by_class_name("review-text")
                                      #value2 is a list
                                      value2 = driver.find_elements_by_class_name("review-date")

                                      for val1 in value1:
                                      print(val1.text)
                                      print "n"
                                      for val2 in value2:
                                      print(val2.text)
                                      print "n"


                                      Output:

                                      review1

                                      review2

                                      review3

                                      date1

                                      date2

                                      date3



                                      Solution:



                                      for val1, val2 in zip(value1,value2):
                                      print (val1.text+':'+val2.text)
                                      print "n"


                                      Output:

                                      review1:date1

                                      review2:date2

                                      review3:date3







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 28 '17 at 6:39









                                      Manojit BallavManojit Ballav

                                      5315




                                      5315























                                          0














                                          you can use 3 type in one dictionary :



                                          def construct_dictionary_from_lists(names, ages, scores):
                                          end_str_dic = {}
                                          for item_name, item_age, score_item in zip(names, ages, scores):
                                          end_str_dic[item_name] = item_age, score_item
                                          return end_str_dic


                                          print(
                                          construct_dictionary_from_lists(
                                          ["paul", "saul", "steve", "chimpy"],
                                          [28, 59, 22, 5],
                                          [59, 85, 55, 60]
                                          )
                                          )





                                          share|improve this answer






























                                            0














                                            you can use 3 type in one dictionary :



                                            def construct_dictionary_from_lists(names, ages, scores):
                                            end_str_dic = {}
                                            for item_name, item_age, score_item in zip(names, ages, scores):
                                            end_str_dic[item_name] = item_age, score_item
                                            return end_str_dic


                                            print(
                                            construct_dictionary_from_lists(
                                            ["paul", "saul", "steve", "chimpy"],
                                            [28, 59, 22, 5],
                                            [59, 85, 55, 60]
                                            )
                                            )





                                            share|improve this answer




























                                              0












                                              0








                                              0







                                              you can use 3 type in one dictionary :



                                              def construct_dictionary_from_lists(names, ages, scores):
                                              end_str_dic = {}
                                              for item_name, item_age, score_item in zip(names, ages, scores):
                                              end_str_dic[item_name] = item_age, score_item
                                              return end_str_dic


                                              print(
                                              construct_dictionary_from_lists(
                                              ["paul", "saul", "steve", "chimpy"],
                                              [28, 59, 22, 5],
                                              [59, 85, 55, 60]
                                              )
                                              )





                                              share|improve this answer















                                              you can use 3 type in one dictionary :



                                              def construct_dictionary_from_lists(names, ages, scores):
                                              end_str_dic = {}
                                              for item_name, item_age, score_item in zip(names, ages, scores):
                                              end_str_dic[item_name] = item_age, score_item
                                              return end_str_dic


                                              print(
                                              construct_dictionary_from_lists(
                                              ["paul", "saul", "steve", "chimpy"],
                                              [28, 59, 22, 5],
                                              [59, 85, 55, 60]
                                              )
                                              )






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Jan 14 at 21:12









                                              Ahmed Nour Jamal El-Din

                                              7891614




                                              7891614










                                              answered Dec 23 '18 at 9:46









                                              shervin haririshervin hariri

                                              16




                                              16























                                                  -4














                                                  def ncustom_zip(seq1,seq2,max_length):
                                                  length= len(seq1) if len(seq1)>len(seq2) else len(seq2) if max_length else len(seq1) if len(seq1)<len(seq2) else len(seq2)
                                                  for i in range(length):
                                                  x= seq1[i] if len(seq1)>i else None
                                                  y= seq2[i] if len(seq2)>i else None
                                                  yield x,y


                                                  l=[12,2,3,9]
                                                  p=[89,8,92,5,7]

                                                  for i,j in ncustom_zip(l,p,True):
                                                  print i,j
                                                  for i,j in ncustom_zip(l,p,False):
                                                  print i,j





                                                  share|improve this answer


























                                                  • is this my answer is right?

                                                    – Sagar T
                                                    Dec 24 '17 at 14:09











                                                  • what is wrong in my answer.?

                                                    – Sagar T
                                                    Dec 25 '17 at 5:12






                                                  • 6





                                                    As explained in the first comment, it is lacking explanation what your code is doing, why it is better/different from the other options, what its performance and memory implication are etc. Just a code dump is not a good answer on Stack Overflow

                                                    – rene
                                                    Dec 25 '17 at 10:41
















                                                  -4














                                                  def ncustom_zip(seq1,seq2,max_length):
                                                  length= len(seq1) if len(seq1)>len(seq2) else len(seq2) if max_length else len(seq1) if len(seq1)<len(seq2) else len(seq2)
                                                  for i in range(length):
                                                  x= seq1[i] if len(seq1)>i else None
                                                  y= seq2[i] if len(seq2)>i else None
                                                  yield x,y


                                                  l=[12,2,3,9]
                                                  p=[89,8,92,5,7]

                                                  for i,j in ncustom_zip(l,p,True):
                                                  print i,j
                                                  for i,j in ncustom_zip(l,p,False):
                                                  print i,j





                                                  share|improve this answer


























                                                  • is this my answer is right?

                                                    – Sagar T
                                                    Dec 24 '17 at 14:09











                                                  • what is wrong in my answer.?

                                                    – Sagar T
                                                    Dec 25 '17 at 5:12






                                                  • 6





                                                    As explained in the first comment, it is lacking explanation what your code is doing, why it is better/different from the other options, what its performance and memory implication are etc. Just a code dump is not a good answer on Stack Overflow

                                                    – rene
                                                    Dec 25 '17 at 10:41














                                                  -4












                                                  -4








                                                  -4







                                                  def ncustom_zip(seq1,seq2,max_length):
                                                  length= len(seq1) if len(seq1)>len(seq2) else len(seq2) if max_length else len(seq1) if len(seq1)<len(seq2) else len(seq2)
                                                  for i in range(length):
                                                  x= seq1[i] if len(seq1)>i else None
                                                  y= seq2[i] if len(seq2)>i else None
                                                  yield x,y


                                                  l=[12,2,3,9]
                                                  p=[89,8,92,5,7]

                                                  for i,j in ncustom_zip(l,p,True):
                                                  print i,j
                                                  for i,j in ncustom_zip(l,p,False):
                                                  print i,j





                                                  share|improve this answer















                                                  def ncustom_zip(seq1,seq2,max_length):
                                                  length= len(seq1) if len(seq1)>len(seq2) else len(seq2) if max_length else len(seq1) if len(seq1)<len(seq2) else len(seq2)
                                                  for i in range(length):
                                                  x= seq1[i] if len(seq1)>i else None
                                                  y= seq2[i] if len(seq2)>i else None
                                                  yield x,y


                                                  l=[12,2,3,9]
                                                  p=[89,8,92,5,7]

                                                  for i,j in ncustom_zip(l,p,True):
                                                  print i,j
                                                  for i,j in ncustom_zip(l,p,False):
                                                  print i,j






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Dec 25 '17 at 8:16

























                                                  answered Dec 24 '17 at 14:01









                                                  Sagar TSagar T

                                                  271110




                                                  271110













                                                  • is this my answer is right?

                                                    – Sagar T
                                                    Dec 24 '17 at 14:09











                                                  • what is wrong in my answer.?

                                                    – Sagar T
                                                    Dec 25 '17 at 5:12






                                                  • 6





                                                    As explained in the first comment, it is lacking explanation what your code is doing, why it is better/different from the other options, what its performance and memory implication are etc. Just a code dump is not a good answer on Stack Overflow

                                                    – rene
                                                    Dec 25 '17 at 10:41



















                                                  • is this my answer is right?

                                                    – Sagar T
                                                    Dec 24 '17 at 14:09











                                                  • what is wrong in my answer.?

                                                    – Sagar T
                                                    Dec 25 '17 at 5:12






                                                  • 6





                                                    As explained in the first comment, it is lacking explanation what your code is doing, why it is better/different from the other options, what its performance and memory implication are etc. Just a code dump is not a good answer on Stack Overflow

                                                    – rene
                                                    Dec 25 '17 at 10:41

















                                                  is this my answer is right?

                                                  – Sagar T
                                                  Dec 24 '17 at 14:09





                                                  is this my answer is right?

                                                  – Sagar T
                                                  Dec 24 '17 at 14:09













                                                  what is wrong in my answer.?

                                                  – Sagar T
                                                  Dec 25 '17 at 5:12





                                                  what is wrong in my answer.?

                                                  – Sagar T
                                                  Dec 25 '17 at 5:12




                                                  6




                                                  6





                                                  As explained in the first comment, it is lacking explanation what your code is doing, why it is better/different from the other options, what its performance and memory implication are etc. Just a code dump is not a good answer on Stack Overflow

                                                  – rene
                                                  Dec 25 '17 at 10:41





                                                  As explained in the first comment, it is lacking explanation what your code is doing, why it is better/different from the other options, what its performance and memory implication are etc. Just a code dump is not a good answer on Stack Overflow

                                                  – rene
                                                  Dec 25 '17 at 10:41


















                                                  draft saved

                                                  draft discarded




















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid



                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1663807%2fhow-to-iterate-through-two-lists-in-parallel%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                                  Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                                                  A Topological Invariant for $pi_3(U(n))$