Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pythonic way to unpack tuples? [duplicate]

Tags:

python

tuples

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]) 
like image 820
user132262 Avatar asked Feb 10 '10 16:02

user132262


People also ask

How do you find duplicates in tuples?

Initial approach that can be applied is that we can iterate on each tuple and check it's count in list using count() , if greater than one, we can add to list. To remove multiple additions, we can convert the result to set using set() .

How do I unpack a list of tuples?

If you want to unzip your list of tuples, you use the combination of zip() method and * operator.

Can tuples have duplicates in Python?

Tuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members. Sets Sets are a collection that is unordered and unindexed. They are mutable (changeable) but do not allow duplicate values to be held.

How does tuple unpacking work in Python?

Unpacking Tuples When we put tuples on both sides of an assignment operator, a tuple unpacking operation takes place. The values on the right are assigned to the variables on the left according to their relative position in each tuple . As you can see in the above example, a will be 1 , b will be 2 , and c will be 3 .


1 Answers

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] 
like image 57
Eli Bendersky Avatar answered Sep 30 '22 17:09

Eli Bendersky