Converting To A Set, Dict, Or Tuple

Converting to a set

A new set object can be produced from a list by passing the list to the set() function.

Duplicate values are eliminated, so set([1,1,1]) produces {1}.

Order is not preserved, so set([1,2,3,1,1]) might produce {1,2,3}, {1,3,2}, or {2,3,1}

Converting to a dictionary

A new dictionary can be produced from a list of (key, value) pairs by passing the list to the dict() function.

dict([('a',1), ('b',2), ('c',3)]) will produce {'a':1, 'b':2, 'c':3}

Converting to a tuple

A new tuple can be produced from a list by passing the list to the tuple() function. The order of the items is preserved.

tuple([1, 2, 3]) would produce (1, 2, 3)

No comments:

Post a Comment