Tuples
Tuples are identical to lists, except that they are immutable (they can't be changed).
Tuples are created with parentheses ()
:
my_tuple = (1, 2, 3)
my_tuple[1] = 4 # Won't work
Contrast this with lists:
my_list = [1, 2, 3]
my_list[1] = 4 # Works -> my_list is now [1, 4, 3]
Tuples Indexing
Similar to lists, you can also call elements in a tuple by index:
tip
These examples are shown with Tuples, but these also work with Lists.
You can also call elements in a tuple by index:
fruits_tuple = ('apple', 'banana', 'orange')
fruits_tuple[0] # 'apple'
fruits_tuple[1] # 'banana'
fruits_tuple[2] # 'orange'
If you want to convert a tuple to a list, you can use the list
function:
my_list = list((1, 2, 3)) # [1, 2, 3]
Tuples Slicing
Similar to lists, you can also slice a tuple:
fruits_tuple[0:2] # ('apple', 'banana')
Loops with tuples
You can also iterate through a tuple the same way you would with a list.
for fruit in fruits_tuple:
print(fruit)
Output: apple banana orange
tip
Lists are much easier to work with.
If you want to convert a tuple to a list, you can use the list
function:
my_list = list((1, 2, 3))