Enumerate, Zip, Sorted, Items, Iteritems built-in functions in Python
- Get link
- X
- Other Apps
Enumerate, Zip, Sorted, Items, Iteritems built-in functions in Python
Python provides several built-in functions for manipulating data, and in this blog post, we will explore some of the most common functions used for iteration and sorting. These functions are:
Enumerate
Zip
Sorted
Items
Iteritems
The enumerate
function is used to loop over a sequence while keeping track of the index of each item. It returns a tuple of the index and the item, which can be unpacked and used inside the loop. Here is an example:
fruits = ['apple', 'banana', 'orange'] for index, fruit in enumerate(fruits): print(index, fruit)
enumerate
to loop over a list of fruits and print the index and the fruit name to the console. The output will be:- Zip
The zip
function is used to combine two or more sequences into a single sequence of tuples. It returns an iterator that can be looped over or converted to a list. Here is an example:
numbers = [1, 2, 3] letters = ['a', 'b', 'c'] for num, letter in zip(numbers, letters): print(num, letter)
zip
to combine two lists of numbers and letters into a sequence of tuples. The output will be:- Sorted
The sorted
function is used to sort a sequence of items in ascending order. It returns a new sorted list and does not modify the original list. Here is an example:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] sorted_numbers = sorted(numbers) print(sorted_numbers)
sorted
to sort a list of numbers in ascending order. The output will be:- Items
items
function is used to loop over the key-value pairs in a dictionary. It returns a sequence of tuples where each tuple contains a key and its corresponding value. Here is an example:items
to loop over a dictionary of fruits and their quantities. The output will be:- Iteritems
iteritems
function is used to loop over the key-value pairs in a dictionary. It returns an iterator that can be looped over or converted to a list. Here is an example:In this example, we used iteritems
to loop over a dictionary of fruits and their quantities. The output will be the same as the items
example above.
Conclusion
In conclusion, Python provides several built-in functions for iterating over data and sorting it. The enumerate
function is used to loop over a sequence while keeping track of the index of each item. The zip
function is used to combine two or more sequences into a single sequence of tuples.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments