Python - Loop Tuples 1
Python - Loop Tuples 1
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the
tuple is created.
Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert
the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other
ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it
into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one
item, (or many), create a new tuple with the item(s), and add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Note: When creating a tuple with only one item, remember to include a comma after the
item, otherwise it will not be identified as a tuple.
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:
Example
Packing a tuple:
fruits = ("apple", "banana", "cherry")
But, in Python, we are also allowed to extract the values back into variables. This is called
"unpacking":
Example
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
print(green)
print(yellow)
print(red)
Note: The number of variables must match the number of values in the tuple, if not, you
must use an asterisk to collect the remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the
variable name and the values will be assigned to the variable as a list:
Example
Assign the rest of the values as a list called "red":
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
print(green)
print(yellow)
print(red)
If the asterisk is added to another variable name than the last, Python will assign values to
the variable until the number of values left matches the number of variables left.
Example
Add a list of values the "tropic" variable:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
print(green)
print(tropic)
print(red)
You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The for loop does not require an indexing variable to set beforehand.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Example
Exit the loop when x is "banana", but this time the break comes before the print:
With the continue statement we can stop the current iteration of the loop, and continue
with the next:
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but
not including 6):
Example
Using the start parameter:
for x in range(2, 6):
print(x)
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
for loops cannot be empty, but if you for some reason have a for loop with no content, put
in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
Python - Join Tuples
Example
Join two tuples:
tuple1 = ("a", "b”, "c")
tuple2 = (1, 2, 3)
Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you can use
the * operator:
Example
Multiply the fruits tuple by 2:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
Method Description
index() Searches the tuple for a specified value and returns the position of
where it was found
x = thistuple.count(5)
print(x)
Definition and Usage
The count() method returns the number of times a specified value appears in the tuple.
Syntax
tuple.count(value)
Parameter Values
Parameter Description
Example
Search for the first occurrence of the value 8, and return its position:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)
Syntax
tuple.index(value)
Parameter Values
Parameter Description