Tuple is another data type in Python. A tuple consists of values separated by commas. Tuples are always enclosed in parentheses. Tuples are for immutable. Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Empty tuples are constructed by an empty pair of parentheses. Tuple with one item is constructed by following a value with a comma.
x = () # empty tuple x = (0,) # one item tuple x = (0, 1, 2, "abc") # four item tuple: indexed x..x x = 0, 1, 2, "abc" # parenthesis are optional x = (0, 1, 2, 3, (1, 2)) # nested subtuples y = x # indexed item y = x # indexed subtuple x = (0, 1) * 2 # repeat x = (0, 1, 2) + (3, 4) # concatenation for item in x: print item # iterate through tuple b = 3 in x # test tuple membership
Recommended Python Training
For Python training, our top recommendation is DataCamp.