114

This is ugly. What's a more Pythonic way to do it?

import datetime

t= (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6])
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user132262
  • 1,837
  • 4
  • 16
  • 17

2 Answers2

158

Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:

t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])

This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]
michen00
  • 764
  • 1
  • 8
  • 32
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • 7
    It works for arbitrary iterables. – Mike Graham Feb 10 '10 at 16:36
  • 3
    I'd like to add that this syntax works anywhere (not just in function calls) in python 3.5, so for instance statements like `x, y, z = *(1, 2, 3)` will work without error (as it should have been a long time ago) – Nearoo Jan 01 '16 at 16:05
  • it there a way to do this among other list items? like `my_tuple = ("B", "C"); "%s %s %s" % ("A", *my_tuple)`? – Dannid Mar 24 '16 at 18:10
  • Nevermind - I think this is a limitation of the %s string substitution method. Using `"{} {} {}".format("A", *my_tuple)` instead does the trick. – Dannid Mar 24 '16 at 23:36
  • Does anyone know any details about how Python implements unpacking internally? – dopatraman Nov 17 '17 at 18:37
16

Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists

 dt = datetime.datetime(*t[:7])
trss
  • 915
  • 1
  • 19
  • 35
Charles Beattie
  • 5,739
  • 1
  • 29
  • 32