Files

3.7 KiB

Tuples

1.) Constructing Tuples
2.) Basic Tuple Methods
3.) Immutability
4.) When to Use Tuples
In [ ]:
# Create a tuple
t = (1,2,3)
In [ ]:
# Check len just like a list
len(t)
In [ ]:
# Can also mix object types
t = ('one',2)

# Show
t
In [ ]:
# Use indexing just like we did in lists
t[0]
In [ ]:
# Slicing just like a list
t[-1]

Basic Tuple Methods

Tuples have built-in methods, but not as many as lists do. Let's look at two of them:

In [ ]:
# Use .index to enter a value and return the index
t.index('one')
In [ ]:
# Use .count to count the number of times a value appears
t.count('one')

Immutability

It can't be stressed enough that tuples are immutable. To drive that point home:

In [ ]:
t[0]= 'change'

Because of this immutability, tuples can't grow. Once a tuple is made we can not add to it.

In [ ]:
t.append('nope')

When to use Tuples

You may be wondering, "Why bother using tuples when they have fewer available methods?" To be honest, tuples are not used as often as lists in programming, but are used when immutability is necessary. If in your program you are passing around an object and need to make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.

You should now be able to create and use tuples in your programming as well as have an understanding of their immutability.

Up next Files!

In [ ]: