To get number of specific elements (by value), we can use count()
function:
tuple_names = ("Samantha", "Madonna", "Michael")
result = tuple_names.count("Samantha")
print("Number of Samantha's: ", result)
Result:
Number of Samantha's: 1
>>>
We can locate position of specific element (by value) using index()
function:
tuple_names = ("Samantha", "Madonna", "Michael")
pos = tuple_names.index("Madonna")
print(pos)
Result:
1
>>>
If we grab value from keyboard, it's easy to find first location, and total number of elements:
tuple_names = ("Samantha", "Madonna", "Michael")
x = input("Enter name to check: ")
print("Number of them: ", tuple_names.count(x))
print("First occurence at position: ", tuple_names.index(x))
Result:
Enter name to check: Madonna
Number of them: 1
First occurence at position: 1
>>>
Tuples are easy to work with.
Next tutorial will be dedicated to Sets.
No comments:
Post a Comment