You will study the basic grammar of Python 3 by referring to "Introduction to Python 3" by O'Reilly Japan. I hope it will be helpful for those who want to study Python in the same way.
Let's compare the code that retrieves the values in the list by iterating.
>>> target = ['AAA', 'BBB', 'CCC']
>>> current = 0
>>> while current < len(target):
... print(target[current])
... current += 1
...
AAA
BBB
CCC
>>> target = ['AAA', 'BBB', 'CCC']
>>> for out in target:
... print(out)
...
AAA
BBB
CCC
The second code is better Python-like code. Since a list is a Python iterator (corresponding to an iterator) object, processing it with a for statement retrieves the elements of the list one by one.
Besides lists, there are Python iterator objects like strings, tuples, dictionaries, sets, and more.
>>> target = 'python'
>>> for out in target:
... print(out)
...
p
y
t
h
o
n
>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for out in num:
... print(out)
...
0
1
2
>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for out in num.keys():
... print(out)
...
0
1
2
>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for out in num.values():
... print(out)
...
zero
one
two
>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for out in num.items():
... print(out)
...
(0, 'zero')
(1, 'one')
(2, 'two')
When processing retrieval and assignment in one step
>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for key, value in num.items():
... print('key:', key, 'value:', value)
...
key: 0 value: zero
key: 1 value: one
key: 2 value: two
You can use zip () to iterate over multiple sequences in parallel.
>>> list1 = ['1', '2', '3']
>>> list2 = ['A', 'B', 'C']
>>> list3 = ['one', 'two', 'three']
>>> for out1, out2, out3 in zip(list1, list2, list3):
... print('list1:', out1, 'list2', out2, 'list3', out3)
...
list1: 1 list2 A list3 one
list1: 2 list2 B list3 two
list1: 3 list2 C list3 three
>>> list1 = ['1', '2', '3']
>>> list2 = ['A', 'B', 'C']
>>> list( zip(list1, list2) )
[('1', 'A'), ('2', 'B'), ('3', 'C')]
>>> list1 = ['1', '2', '3']
>>> list2 = ['A', 'B', 'C']
>>> dict( zip(list1, list2) )
{'1': 'A', '2': 'B', '3': 'C'}
>>> for x in range(0, 3):
... print(x)
...
0
1
2
>>> list( range(0, 3) )
[0, 1, 2]
Recommended Posts