Example of list loop usage in python

  • 2020-04-02 14:18:52
  • OfStack

This article illustrates the use of a list loop in python. Share with you for your reference. Specific usage analysis is as follows:

One of Python's powerful features is its parsing of lists, which provides a compact way to map one list to another by applying a function to each element in a list.
The instance

a = ['cat', 'window', 'defenestrate']
for x in a:
     print x, len(x)
for x in [1, 2, 3]: print x,      # iteration Loop through a list: for in
a = ['cat', 'window', 'defenestrate']
for x in a[:]: # make a slice copy of the entire list
    if len(x) > 6: a.insert(0, x)
 
print a

Operation results:


cat 3
window 6
defenestrate 12
1 2 3 ['defenestrate', 'cat', 'window', 'defenestrate']

 
According to the array length to operate:
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
     print i, a[i]

Operation results:

0 Mary
1 had
2 a
3 little
4 lamb

words = ['A', 'B', 'C', 'D', 'E']
for word in words:
    print word

Operation results:

A
B
C
D
E

List analysis:

>>> li = [1, 9, 8, 4]
>>> [elem*2 for elem in li]     
[2, 18, 16, 8]
>>> li                          
[1, 9, 8, 4]
>>> li = [elem*2 for elem in li]
>>> li
[2, 18, 16, 8]

To understand it, let's look from right to left. Li is a list to be mapped. Python loops through each element in li. For each element, do the following: first temporarily assign its value to the variable elem, then Python applies the function elem*2 to the calculation, and finally appends the result to the list to be returned.
 
Note that parsing the list does not change the original list.
 
It is safe to assign the parsing result of a list to the variable that maps to it. Don't worry about competition or anything weird happening. Python creates a new list in memory, and when the list is parsed, Python assigns the result to a variable.

I hope this article has helped you with your Python programming.


Related articles: