Home > Net >  How do I print every element after the first, twice?
How do I print every element after the first, twice?

Time:02-01

The usage case would be for dates.... for example:

Monday, Tuesday
Tuesday, Wednesday
Wednesday, Thursday
Thursday, Friday.

Or using numerics:

0, 1
1, 2
2, 3
3, 4
4, 5
5, 6

If I have a list of numbers like numbers = [0, 1, 2, 3, 4, 5, 6], I've tried:

for x, y in zip(numbers[::2], numbers[1::2]):
    print(x, y)

But this doesn't work.

CodePudding user response:

Try the following:

numbers = [0, 1, 2, 3, 4, 5, 6]

for x, y in zip(numbers, numbers[1:]):
    print(x, y)

# 0 1
# 1 2
# 2 3
# 3 4
# 4 5
# 5 6

From python 3.10, you can use itertools.pairwise instead.

  •  Tags:  
  • Related