zip object is not reversible when trying to reverse zip result

Viewed 50

I would like to print the current element, from the end, and the elements on its right.

This is my script:

lst = ["namaste", "hello", "ciao", "salut"]

for el, nxt in reversed(zip(lst, lst[1:]))
    print(el, nxt)

unfortunately I am getting:

zip object is not reversible

I would like to get this result:

Ciao, Salut
Hello, Ciao
Namaste, Hello
  • How can I do?
2 Answers

You can use zip:

l = ["Namaste", "Hello", "Ciao", "Salut"]

for a,b in zip(l[-2::-1], l[::-1]):
    print(f'{a}, {b}')

output:

Ciao, Salut
Hello, Ciao
Namaste, Hello

My code is kinda bulk but it works:

li = ["namaste", "hello", "ciao", "salut",'aymen','khalid']
if len(li)%2 != 0:
    li.append("")
for names in range(0,len(li),2):
    if names%2 == 0:
        print(li[names],li[names+1])
else:
    print(li[names])
Related