Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an integer to all values in a tuple

What is the recommended/most pythonic way of editing a tuple in code like that shown below?

tup_list = [(1, 2), (5, 0), (3, 3), (5, 4)]
max_tup = max(tup_list)
my_tup1 = (max_tup[0] + 1, max_tup[1] + 1)
my_tup2 = tuple(map(lambda x: x + 1, max_tup))
my_tup3 = max([(x+1, y+1) for (x, y) in tup_list])

Which of the three methods above is preferred, or is there a better way to do this? (Should of course return (6, 5) in this example).

There is a temptation to do something like

my_tup = max(tup_list)[:] + 1

or

my_tup = max(tup_list) + (1, 1)

however neither of these work obviously.

like image 818
Siwel Avatar asked Jul 20 '16 12:07

Siwel


1 Answers

Just use a generator expression with tuple:

my_tup = tuple(x+1 for x in max_tup)
# or my_tup = tuple(x+1 for x in max(tup_list))
like image 156
chepner Avatar answered Oct 13 '22 00:10

chepner