Invisible link to canonical for Microformats

Tuples


Tuples

Tuple is an ordered collection that can’t be changed.

  • Duplicate values are allowed.
  • Can be of any data types.
  • Belong to class tuple.
  • Negative indexing is allowed.

len() is used to find length of tuple.

songs = ("What Would You Do", "Shame", "Hangin'")
print(len(songs)) # 3

To create a tuple with only one item, add comma after the item.

Access tuple items using their index number :

print(songs[2]) # Hangin'

You can specify a range of indexes the same way you do in lists.

mountain_sound = ("Hold your horses now", "we sleep until the sun goes down", "Through the woods, we ran", "deep into the mountain sound")
print(mountain_sound[1:3])
"""
('we sleep until the sun goes down', 'Through the woods, we ran')
"""

Use in operator to check if item exists in tuple.

i = 0
if "hold" in mountain_sound:
    print("yes")
# yes

Although tuples are immutable, they can be converted into list to change them, then converted back to tuple.

lyrics = list(mountain_sound)
lyrics.append("We sleep until the sun goes down")
new = tuple(lyrics)
print(new)
"""
('Hold your horses now', 'we sleep until the sun goes down', 'Through the woods, we ran', 'deep into the mountain sound', 'We sleep until the sun goes down')
"""

Or, we can use single-value tuple and add it to current tuple.

lyrics = ("We sleep until the sun goes down",)
mountain_sound += lyrics
print(mountain_sound)
"""
('Hold your horses now', 'we sleep until the sun goes down', 'Through the woods, we ran', 'deep into the mountain sound', 'We sleep until the sun goes down')
"""

Use the same workaround to remove items.

lyrics = list(mountain_sound)
lyrics.pop(2)
new = tuple(lyrics)
print(new)
"""
('Hold your horses now', 'we sleep until the sun goes down', 'deep into the mountain sound')
"""

Assigning values to it is called packing a tuple. If we extract values back into variable, we unpack a tuple.

bastille = ("Weight of Living Pt. I", "Glory", "Of The Night")
(a, b, c) = bastille
print(a) # Weight of Living Pt. I
print(b) # Glory
print(c) # Of The Night

Use an asterisk if variables are lesser than number of values.

bastille = ("Weight of Living Pt. I", "Glory", "Of The Night", "Shame", "Pompeii")
(a, b, c) = bastille
print(a) # Weight of Living Pt. I
print(b) # Glory
print(c) # ['Of The Night', 'Shame', 'Pompeii']

Use for and while loops to iterate through the tuple.


for i in bastille:
    print(i)
"""
Weight of Living Pt. I
Glory
Of The Night
"""

i = 0
while i < len(bastille):
    print(bastille[i])
    i +=1
"""
Weight of Living Pt. I
Glory
Of The Night
"""