#swe #flashcards

Related: Software engineering | 8-15-2025 Dictionaries | 8-22-2025 Sets | 8-21-2025 Packing and Unpacking

Tuples


Tuples are an immutable data type once they’ve been created they can not be changed

Syntax

tuple()

Strings are iterable, so using a single str as an argument to the tuple() constructor can have surprising results:

multiple_elements_string = tuple("Timbuktu") # String elements (characters) are iterated through and added to the tuple

print(multiple_elements_string)

Accessing tuples

Elements within a tuple can be accessed via bracket notation using a 0-based index number from the left or a -1-based index number from the right.

tuple_1 = ("bread", "beans", "bannanas")
print(tuple_1[0]) # output is 'bread'

Tuple Concatenation

Tuples can be concatenated using plus + operator, which unpacks each tuple creating a new, combined tuple

new_via_concatenate = ("George", 5) + ("cat", "Tabby")
("George", 5, "cat", "Tabby")


first_group = ("cat", "dog", "elephant")#likewise, using the multiplication operator * is the equivalent of using + n times

multiplied_group = first_group * 3
('cat', 'dog', 'elephant', 'cat', 'dog', 'elephant', 'cat', 'dog', 'elephant')

print(new_via_concatenate) 
print(first_group)
print(multiplied_group)

Tuple Methods

Python has two built-in methods that you can use on tuples

id: fxDKQWGSAb3AwJPo88VBw
===
count():	`Returns the number of times a specified value occurs in a tuple`

===
index():	`Searches the tuple for a specified value and returns the position of where it was found`

Adding items to tuples

Since tuples are immutable they do not have a built in append() method but you can add items to a tuple by:

Converting to a list

tuple_2 = ('sam','sophia''sonia')
x = list(tuple_2) # turn tuple to list which has built in append
x.append('lillian')
tuple_2 = tuple(x)
print(tuple_2)

Add a tuple to a tuple

tuple_3 = ('sam','sophia','sonia')
x = ("lillian",)
tuple_3 += x

print(tuple_3)

Removing one index from a tuple

tuple_4 = ('sam','sophia','sonia')
new_tuple = (tuple_4[0],tuple_4[1])
print(tuple_4)
print(new_tuple)