AD28
AD28

Reputation: 1

Add consecutive numbering to list of tuples

i have lists which look like:

[('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]

and what I'm trying to get should look like:

[('1', 'A', 'B', 'C'), ('2', 'D', 'E', 'F'), ('3', 'G', 'H', 'I')]

Upvotes: 0

Views: 58

Answers (2)

Roland Smith
Roland Smith

Reputation: 43495

Use a list comprehension with unpacking.

In [1]: t = [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]

In [2]: [(str(i), *j) for i, j in enumerate(t, start=1)]
Out[2]: [('1', 'A', 'B', 'C'), ('2', 'D', 'E', 'F'), ('3', 'G', 'H', 'I')]

It's also quite fast.

In [3]: %timeit([(str(i), *j) for i, j in enumerate(t, start=1)])
100000 loops, best of 3: 5.91 µs per loop

This does not work in Python <3.5. This behavior was introduced in PEP 448.

Upvotes: 1

Jan van der Vegt
Jan van der Vegt

Reputation: 1511

You can use enumerate to pack them into 2-tuples, and then map them back into one tuple:

my_list = [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]
new_list = [(str(x[0]),)+x[1] for x in enumerate(my_list, start=1)]

First object in the enumerate will be:

(1, ('A', 'B', 'C'))

We turn the number into a 1-tuple, map it into a string and then add the original tuple to it.

EDIT: Some different methods with time added

my_list = [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]*1000

new_list = [(str(x[0]+1),)+x[1] for x in enumerate(my_list)]
## 1000 loops, best of 3: 815 µs per loop

new_list = [(str(x[0]),)+x[1] for x in enumerate(my_list, start=1)]
## 1000 loops, best of 3: 766 µs per loop, by schwobaseggl

new_list = map(lambda x:(str(x[0]),)+x[1],enumerate(my_list, start=1))
## 1000 loops, best of 3: 989 µs per loop

new_list = [(str(index),)+values for index, values in enumerate(my_list, start=1)]
## 1000 loops, best of 3: 669 µs per loop, by Donkey Kong

Upvotes: 2

Related Questions