DEV Community

Vicki Langer
Vicki Langer

Posted on • Edited on

Charming the Python: Tuples

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') 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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) 
Enter fullscreen mode Exit fullscreen mode

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) 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

Series based on

Top comments (0)