If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.
Tuples
A tuple can be a collection of multiple data types. Tuples are ordered and immutable. Immutable means unchangeable or unmodifiable.
Creating
# empty tuple to show syntax
empty_tuple = ()
# A not empty tuple
dogs = ('chihuahua', 'golden retriever', 'german shepherd', 'mutt')
Accessing Items
You can access items in a tuple similar to accessing characters in a string.
chihuahua | golden retriever | german shepherd | mutt |
---|---|---|---|
0 | 1 | 2 | 3 |
-4 | -3 | -2 | -1 |
dogs = ('chihuahua', 'golden retriever', 'german shepherd', 'mutt')
print(dogs[1])
>>> golden retreiver
print(dogs[-2])
>>> german shepherd
Slicing
dogs = ('chihuahua', 'golden retriever', 'german shepherd', 'mutt')
print(dogs[1:2]) # will print index 1 to 2
>>> golden retriever, german shepherd
print(dogs[-3:-1]) # will print index -3 up to but not including -1
>>> golden retriever, german shepherd
Casting to a List
Tuples are immutable/not-changeable, while lists are mutable/changeable.
In order to update the contents of a tuple, you may change a tuple into a list. This is call casting into a list.
dogs = ('chihuahua', 'golden retriever', 'german shepherd', 'mutt')
dogs_list = list(dogs)
After making adjustments to your new lest, don't forget to change it back to a tuple.
dogs_list = ['chihuahua', 'golden retriever', 'german shepherd', 'mutt']
dogs = tuple(dogs_list)
Joining
dogs = ('chihuahua', 'golden retriever', 'german shepherd', 'mutt')
cats = ('domestic shorthair', 'persian', 'siamese')
pets = dogs + cats
print(pets)
>>> chihuahua, golden retriever, german shepherd, mutt, domestic shorthair, Persian, siamese
Deleting
Because tuples are immutable, you cannot delete single items in a tuple. However, you can delete a whole tuple
dogs = ('chihuahua', 'golden retriever', 'german shepherd', 'mutt')
del dogs
print(dogs) # this will error because 'dogs' no longer exists
Series based on
Top comments (0)