Is it possible to start a program like this in python 3:

a = ['a','b','c','d'] for k,j in a: print(k,j) 

If so, how to fix it so that it works?

  • What are k and j? Value and index? - gil9red
  • No, they both have to output the same array. At the output, and k, everything in the array a displays and j, all that in the array outputs - Ilnyr
  • for k in a: print(k,k) ??? - gil9red

1 answer 1

If you just need to output the same thing for one iteration, then you can simply output the same thing two times (sincerely yours, Captain Obvious):

 a = ['a', 'b', 'c', 'd'] for k in a: print(k, k) 

If you literally do what you want to do, then you can use the zip function, passing the original list to it two times:

 a = ['a', 'b', 'c', 'd'] for k, j in zip(a, a): print(k, j) 

But there is no special practical sense in this; it is essentially over-engineering.

The meaning of this design appears if you need to parallelly proceed along two different lists, for example:

 a = ['a', 'b', 'c', 'd'] b = ['w', 'x', 'y', 'z'] for k, j in zip(a, b): print(k, j) 

This loop will output the corresponding elements of both lists in pairs (i.e. a and w , b and x , etc.)

  • zip(a, a) looks like zip(it, it) where it=iter(a) , but the result is certainly different. No need to use zip(a,a) to avoid confusion. Better to just print(k,k) limited (the first example). - jfs
  • @jfs, yes, with iterators / generators, it has been so tricky several times, especially when you do "debugging with prints" after outputting, say, list(it) then suddenly (actually expected) it turns out that it already empty. - insolor
  • one
    zip(it, it) is an idiom that allows you to go around the iterator in pairs: ('a', 'b') , ('c', 'd') . In this case, the fact that it is consumed during the passage is intentionally used. For example, if the input contains 6 elements, then to get 3 elements at a time: zip(*[iter(iterable)]*3) . If a non-multiple number, then you can zip_longest() , see the grouper() recipe in the documentation. - jfs
  • @jfs, yes, I saw a similar example, but only today I understood how it works. - insolor