2

How to iterate over [(1,2,3), (2,3,1), (1,1,1)] while splitting each tuple into a head and a tail? I am searching concise an pythonic way like this:

for h, *t in [(1,2,3), (2,3,1), (1,1,1)]:
    # where I want t to be a tuple consisting of the last two elements
    val = some_fun(h)
    another_fun(val, t)

The above doesn't work for python 2.7.

Fibo Kowalsky
  • 1,198
  • 12
  • 23

1 Answers1

1

You could use a map to and list slicing:

for h, t in map(lambda x: (x[0], x[1:]), [(1,2,3), (2,3,1), (1,1,1)]):
    print("h = %s, t=%s"%(h, t))
#h = 1, t=(2, 3)
#h = 2, t=(3, 1)
#h = 1, t=(1, 1)
pault
  • 41,343
  • 15
  • 107
  • 149