How to create a circular list in one line of code?

116 views Asked by At

Given the following list:

labels = [0, 1, 2, 3, 4]

I wish I could obtain the following by using just one line of code:

['0-1', '1-2', '2-3', '3-4', '4-0']

I can do this with 2 lines of code:

pairwise_labels = [f"{i}-{i+1}" for i in range(len(labels)-1)]
pairwise_labels.append(f"{len(labels)-1}-0")

With just one line, my code will be drastically reduced, as I always need to create an if for the last case to close the loop.

5

There are 5 answers

0
Timeless On

One option would be to use pairwise (New in version 3.10) :

from itertools import pairwise

labels = [0, 1, 2, 3, 4]

pairwise_labels = [f"{x}-{y}" for x, y in pairwise(labels + [labels[0]])]

Output :

print(pairwise_labels)

#['0-1', '1-2', '2-3', '3-4', '4-0']
1
Huzaifa Zahoor On

You can do this in one line using modular arithmetic.

pairwise_labels = [f"{labels[i]}-{labels[(i+1)%len(labels)]}" for i in range(len(labels))]
0
Luca Anzalone On

Your one liner:

pairwise_labels = [f'{a}-{b}' for a, b in zip(labels, labels[1:] + [labels[0]])]
0
Corralien On

You can slice your list:

>>> [f'{i}-{j}' for i, j in zip(labels, labels[1:] + labels[:1])]

['0-1', '1-2', '2-3', '3-4', '4-0']
0
Alain T. On

You can leverage Python's ability to use negative indexes:

labels = [0, 1, 2, 3, 4]

pl = [f"{a}-{labels[i]}" for i,a in enumerate(labels,1-len(labels))]

print(pl)

['0-1', '1-2', '2-3', '3-4', '4-0']