Ujjwal Singh Baghel
Ujjwal Singh Baghel

Reputation: 393

I want to print the pair of elements of a list starting from 1 index

I have a list containing

l = ['in','1out','1in','2out','2in','3out','3in']

and i want to pair the list starting from the index 1 and so on. I have written as-

zip(l[1::2], l[2::1])

It prints as-

[('1out', 'in'), ('2out', '1in'), ('3out', '2in')]

But I want as-

[('1out', '1in'), ('2out', '2in'), ('3out', '3in')]

Thanks if anyone could help..

Upvotes: 1

Views: 54

Answers (1)

Alexander
Alexander

Reputation: 109726

You were close. Just need the l[2::2] instead of l[2::1] for the second argument to the zip function. You need to skip every other value starting with the second.

>>> list(zip(l[1::2], l[2::2]))
[('1out', '1in'), ('2out', '2in'), ('3out', '3in')]

Upvotes: 3

Related Questions