for
and while
loops are not your only options. Python provides several powerful inbuilt looping functions that not only simplify your code but also make it more efficient. In this guide, we will explore the most commonly used inbuilt looping functions, their advantages, and practical examples to help you leverage their power. enumerate()
function adds a counter to an iterable and returns it as an enumerate object. This is particularly useful when you need both the index and the value of each element in a loop.list1 = ["Python", 42, 3.14]
obj = enumerate(list1)
print(list(obj))
[(0, 'Python'), (1, 42), (2, 3.14)]
zip()
function combines elements of multiple iterables based on their index. It returns a zip object, which can be converted into a list or a tuple for easy readability.list1 = ["I", "am", "learning"]
list2 = ["Python", "with", "examples"]
obj = zip(list1, list2)
print(list(obj))
[('I', 'Python'), ('am', 'with'), ('learning', 'examples')]
items()
function is used to iterate over a dictionary’s key-value pairs in Python 3.x. This function is straightforward and memory-efficient.dict1 = {"Name": "Alice", "Age": 25, "Country": "USA"}
obj = dict1.items()
print(list(obj))
[('Name', 'Alice'), ('Age', 25), ('Country', 'USA')]
sorted()
function returns a sorted version of an iterable without modifying the original. It’s particularly useful when you need to sort data temporarily.fruits = ["Banana", "Apple", "Mango"]
obj = sorted(fruits)
print(obj)
print(fruits)
['Apple', 'Banana', 'Mango']
['Banana', 'Apple', 'Mango']
reversed()
function returns the elements of an iterable in reverse order without changing the original data.numbers = [1, 2, 3, 4]
obj = reversed(numbers)
print(list(obj))
print(numbers)
[4, 3, 2, 1]
[1, 2, 3, 4]
Note:iteritems()
is deprecated in Python 3.x but remains relevant for Python 2.x users. It works similarly toitems()
by returning an iterator over dictionary key-value pairs.
dict1 = {"Name": "Alice", "Age": 25, "Country": "USA"}
obj = dict1.iteritems()
print(list(obj))
[('Name', 'Alice'), ('Age', 25), ('Country', 'USA')]
enumerate()
, zip()
, items()
, sorted()
, and reversed()
make data manipulation intuitive and efficient. By using these functions, you can simplify your code, enhance readability, and reduce execution time. While these functions won’t entirely replace for
or while
loops, they are invaluable tools in any Python programmer’s toolkit.Click Here to know know more our program!