» Quick Introduction to Python » 2. Collections » 2.4 Tuples

Tuples

Construct a Tuple

a = ('a', 'b', 'c')

# from a list or any other iterable collection
c = tuple([1, 3, 5]) # (1, 3, 5)

Loop Through Items

a = ("fig", "mango", "watermelon")
for e in a:
    print(e)

Unpack Tuple

a = ("fig", "mango", "watermelon")
item1, item2, item3 = a
print(item1) # fig
print(item2) # mango
print(item3) # watermelon

Check If Item Exists

a = ("fig", "mango", "watermelon")
print("fig" in a) # True
print("cherry" in a) # False

Tuple's Common Methods

count

a = ("fig", "mango", "fig", "watermelon", "fig")
print(a.count("fig")) # 3

index

a = ("fig", "mango", "fig", "watermelon", "fig")
print(a.index("watermelon")) # 3

Code Challenge

Try to modify the code provided in the editor to make a tuple like (1, 'hello', ['a', 'b'], {'a': 1, 'b': 2}, False, (1, 2, 3)).

Loading...
> code result goes here
Prev
Next