Python Advanced Tuple Functions Cheat Sheet with Examples

Python Advanced Tuple Functions Cheat Sheet with Examples




1. reversed() Function

The reversed() function returns a reverse iterator over a sequence (like list, tuple, string).

Example:


my_list = [1, 2, 3, 4]
rev = list(reversed(my_list))
print(rev)

Output:


[4, 3, 2, 1]

2. enumerate() Function

The enumerate() function adds a counter to an iterable and returns it as an enumerate object.

Example:


fruits = ['apple', 'banana', 'cherry']
for index, value in enumerate(fruits):
    print(index, value)

Output:


0 apple
1 banana
2 cherry

3. any() Function

The any() function returns True if any element of the iterable is true.

Example:


values = [0, False, 3, None]
print(any(values))

Output:


True

4. all() Function

The all() function returns True if all elements in the iterable are true.

Example:


values = [1, True, 5]
print(all(values))

Output:


True

Example with False:


values = [1, 0, 5]
print(all(values))

Output:


False

5. zip() Function

The zip() function combines two or more iterables element-wise into tuples.

Example:


names = ['Alice', 'Bob']
scores = [85, 90]
combined = list(zip(names, scores))
print(combined)

Output:


[('Alice', 85), ('Bob', 90)]

6. index() Method (used in list, tuple, etc.)

Returns the first index of the specified value.

Example:


items = ['pen', 'book', 'pen']
print(items.index('pen'))

Output:


0

7. count() Method (used in list, tuple, etc.)

Returns the number of times a value appears in the list/tuple.

Example:


data = [1, 2, 2, 3, 2]
print(data.count(2))

Output:


3

8. del Keyword

The del keyword deletes variables, list elements, or entire objects.

Example: delete element


my_list = [1, 2, 3, 4]
del my_list[1]
print(my_list)

Output:


[1, 3, 4]

Example: delete variable


x = 5
del x
# print(x) → NameError

9. slice() Function

The slice() function returns a slice object used to slice sequences like list, tuple, string.

Example:


my_list = ['a', 'b', 'c', 'd', 'e']
s = slice(1, 4)
print(my_list[s])

Output:


['b', 'c', 'd']

⚠️ You can also use slice(start, stop, step):


print(my_list[slice(0, 5, 2)])

Output:


['a', 'c', 'e']

📚 Related Topics:


📌 Bookmark this blog or follow for updates!

Python Logo

👍 Liked this post? Share it with friends or leave a comment below!

Previous Post Next Post

Contact Form