Skip to content
Search

Python:Tuples

lastmod 2015-04-05created 2015-04-051 edits

Syntax

three_tuple = ('a', 'b', 'c')
empty_tuple = ()
one_tuple = 5,

Unlike lists, tuples do not let you change element values directly, so you have to cut and paste them as you did with strings.

p = (1,2,3)
q = p[:1] + (5,) + p[2:]
## q = (1, 5, 3)
r = p[:1], 5, p[2:]
## r = ((1,), 5, (3,))

List and Tuple

You can also easily convert a tuple to a list and a list to a tuple.

p = (1, 2, 3)
q = list(p) # 튜플 p로 리스트 q로...
## q = [1, 2, 3]
r = tuple(q) # 리스트 q로 튜플 r로...
## r = (1, 2, 3)

Swapping two values

c = 10
d = 20
c, d = d, c

Variadic argument tuples

Put * in front of the argument.

def magu_print(x, y, *rest):
    print x, y, rest
## ...
magu_print(1,2,3,5,6,7,9,10)

The output is as follows.

1 2 (3, 5, 6, 7, 9, 10)

for-each loop when a tuple is returned

for base, dirs, names in os.walk(root):
    pass

Favorite site