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)
Copy the code

Flow chart:

Animals ="dog","cat","pig""bird" for animal: print(animal)#for loop, print needs to be indentedCopy the code

Running results:

dog
cat
pig
bird
Copy the code

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 += I print(result)Copy the code

The running results are as follows:

Calculation of 1 + 2 +... +100 results in: 5050Copy the code

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)Copy the code

The execution result of the program is:

ele = 1
ele = 2
ele = 3
ele = 4
ele = 5
Copy the code

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)
Copy the code

The execution result of the program is as follows:

Three, two, three, three, threeCopy the code

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)
Copy the code

The execution result of the program is:

ele = python
ele = shell
ele = java
Copy the code

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)
Copy the code

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)
Copy the code

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')
Copy the code

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__ ()Copy the code

Lists are converted to tuples

Fruit_list = ['apple','banana','orange'] # fruit_list = ['apple','banana','orange'] # fruit_list = ['apple','banana','orange']Copy the code

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: Fruit_dict.value ()) # convert dictionary keys to lists: List (fruit_dict.value()) # convert dictionary to string: STR (fruit_dict)Copy the code

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)Copy the code