Python: Hidden Features — part 2

Advance techniques for better programming

Pravash
4 min readMar 26, 2024

--

Hi Everyone, In this article I will go throw couple of techniques or features which anyone can use in day to day coding.

In my journey through these Python features, I’ve uncovered techniques that go beyond the ordinary adding a touch of magic to our code.

Lets get started -

1. use next()

Lets see below example -

list_of_dicts = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35}
]

# Target name to search
target_name = 'Bob'

# Using a for-each loop to find the dictionary
for person in list_of_dicts:
if person['name'] == target_name:
print(f"Found: {person}")
break # Exit the loop once the target is found
else:
print("Target not found.")

So, here we are using for each loop to find that target in the dictionary and else statement if the target is not present.

There’s a much concise way of doing this is using next().

The next()function in Python is a built-in function that is used to retrieve the next item from an iterator. It’s part of Python’s iterator protocol, which also includes the iter() function to obtain an iterator from an iterable (like lists, tuples, or strings).

Here’s, the modified code -

list_of_dicts = [
{'name': 'Alice', 'age'…

--

--

Pravash
Pravash

Written by Pravash

I am a passionate Data Engineer and Technology Enthusiast. Here I am using this platform to share my knowledge and experience on tech stacks.

Responses (5)