The Python for loop can iterate over items of any sequence, such as list, string, tuple, dictionary, collection, and other sequence types.

Grammar:

The syntax for the for loop is as follows:

for iterating_var in sequence: statements(s)

Flow chart:

Animals =”dog”,”cat”,”pig””bird”for animal: print(animal)#for loop, print needs to be indented

Running results:

dogcatpigbird

As you can see, with the for loop, the iterated variables are successively assigned and substituted into the body of the loop.

A concrete application of the Python for loop

The for loop does a numeric loop

The most basic use of a for loop is to do a numeric loop.

For example, if you want to sum from 1 to 100, you can execute the following code:

Print (” 1 + 2 +… For I in range(101): result += iprint(result)

The running results are as follows:

Calculation of 1 + 2 +… +100 results in: 5050

In the code above, we use the range() function, which is Python’s built-in function for generating a series of consecutive integers, most commonly used in for loops.

The for loop iterates through lists and tuples

When a for loop iterates through a list or tuple, the iterating variables are successively assigned to each element in the list or tuple and the body of the loop is executed once.

The following program iterates through the list using a for loop:

My_list = [1,2,3,4,5] print(‘ele =’, ele)

The execution result of the program is:

ele = 1ele = 2ele = 3ele = 4ele = 5

In Python, a for loop iterates over a tuple much like a sequence. The following program iterates over a tuple using a for loop:

my_tuple = tuple(“23333”)print(my_tuple)#<<< (‘2’, ‘3’, ‘3’, ‘3’, ‘3’)for value in my_tuple: print(value)

The execution result of the program is as follows:

32333

Note: For a character set, the order of the elements in the set is usually undefined, and the word identifier in “for Word in Words” can also be changed at will.

The for loop iterates through the dictionary

Three dictionary-related methods, items(), keys(), and values(), are often used when iterating through a dictionary using the for loop. If the dictionary is iterated directly using the for loop, iterating variables are successively assigned to the keys in each key-value pair.

my_dic = {‘python’:”1″,\ ‘shell’:”2″,\ ‘java’:”3″}for ele in my_dic: print(‘ele =’, ele)

The execution result of the program is:

ele = pythonele = shellele = java

Keys () returns the same value as traversing the dictionary directly.

Loop iteration key:

d = {‘x’:1,’y’:2,’z’:3} for key in d.keys(): print(key)

In addition, we can iterate over the return values of the dictionary values(), items() methods. Such as:

Loop iteration value:

d = {‘x’:1,’y’:2,’z’:3} for value in d.values(): print(value)

my_dic = {‘python’:”1″,\ ‘shell’:”2″,\ ‘java’:”3″}for ele in my_dic.items(): print(‘ele =’, ele)

The d.tems method can also put key-value pairs back as tuples, and one of the great benefits of a for loop is that you can use sequence unpacking within the loop

The execution result of the program is:

ele = (‘python’, ‘1’)ele = (‘shell’, ‘2’)ele = (‘java’, ‘3’)

Conversion between tuples, lists, and dictionaries

Tuples are converted to lists

Fruits = (‘apple’,’banana’,’orange’) # tuple to list: list(fruit) # tuple to dictionary: fruit.__str__ ()

Lists are converted to tuples

Fruit_list = [‘apple’,’banana’,’orange’] # fruit_list = [‘apple’,’banana’,’orange’] # fruit_list = [‘apple’,’banana’,’orange’]

Dictionaries are converted to tuples

Can use the function of the tuple () and list () converts a dictionary to tuples and lists, but note that here before and after the transformation of the elements of the sequence is different, because the dictionary is similar to the hash, the list is similar to the linked list, tuples similar to list just elements cannot be changed, so, to convert the hash to list and order the same is not feasible. But you can use OrderedDict, a subclass of dictionaries that remembers the order in which elements were added to get an ordered dictionary. The ordered dictionary will not be discussed in depth here, to give a common dictionary example reference, the code is as follows:

fruit_dict = {‘apple’:1, ‘banana’:2, ‘orange’:3} # convert dictionary keys to tuples :tuple(fruit_dict)# convert dictionary values to tuples :tuple(fruit_dict.value()) Fruit_dict (); fruit_dict ();

Strings are converted to tuples

To convert a string to a specified data structure, the string must conform to the format of the specified data structure, with the help of the eval() function

STR = “(1,2,3)”tuple(eval(STR))# convert strings to dictionaries: str = “{‘a’:1 ,’b’,2}”eval(str)

Click 666 to get it for free