Sunday, April 20, 2025

Python Tuples, Operations

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

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...