Looping technique in Python

Looping technique in Python

Python has specific inbuilt functions, due to which it supports numerous looping techniques in several sequential containers. These looping functions and methods are very useful for competitive coding. It can be used in different projects in which user has to use some specific technique with loops for maintaining the whole structure of the program. These techniques help save time and memory space as the user does not have to declare the extra variables for the traditional approach of loops.

Where these looping techniques are used?

Different types of looping techniques are used in the places where the user does not have to manipulate the structure of the code or the orders of the whole containers. Instead, the user has to print the elements for a single-use instance, and no in-place change occurs in the container. These can also be used for saving time and memory.

Looping Techniques by using Python Data Structures:

  • enumerate(): The enumerate() function is used for looping through the containers and for printing the index number with the value present in that specific index.

Example:

Output:

0 Joe
1 waited
2 for
3 the
4 train
5 ,
6 but
7 the
8 train
9 was
10 late
11 .
  • zip(): The zip() function is used for combining the two similar containers, such as dict with dict or list with the list, by printing their values in sequence. The loop will exist only after the end of the smaller container.

Example:

Output:

What is this animal?  this is tiger.
What is this shape?  this is square.
What is this time?  this is 11 o clock.
  • items(): The items() function is used for looping through the dictionary and printing the key and its values in sequence.

Example:

Output:

The key value pair by using items is : 
Joe waited
for the
train but
the train
was late
  • sorted(): The sorted() function is used for printing the container in sorted order. This function does not sort the container, but it is used for printing the container in sorted order, for instance. The user can use the set() function with the sorted() function to remove the duplicate value in the output.

Example 1:

Output:

The list in sorted order is : 
1 1 2 4 4 6 7 
The list in sorted order (without duplicates) is : 
1 2 4 6 7

Example 2:

Output:

Joe
but
for
late
the
train
waited
was
  • reversed(): The reserved() function is used for printing the values of the container in the reversed order.

Example 1:

Output:

The list in reversed order is : 
21 19 17 15 13 11 9 7 5 3 1

Example 2:

Output:

19
17
15
13
11
9
7
5
3
1

Conclusion

In this tutorial, we have discussed the different types of lopping techniques that are useful for saving memories and time.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263493.html

(0)
上一篇 2022年5月30日
下一篇 2022年5月30日

相关推荐

发表回复

登录后才能评论