You can create a list, set type, etc. (collection) using a for statement.
How to write a for statement easily.
・ [Expression for variable in iterable]
└ If you enclose it in [], the output type will be list.
└ {} is a set type
[(i*2) for i in range(5)]
#output
[0, 2, 4, 6, 8]
The output is in list format. Same as below.
python
arrs=[]
for i in range(5):
arr = (i*2)
arrs.append(arr)
arrs
#output
[0, 2, 4, 6, 8]
▼ {} is a set type
{(i*2) for i in range(5)}
#output
{0, 2, 4, 6, 8}
list, range, set, etc.
Str, int, float, etc. that can only have one data are not collections.
Iterable is a general term for repeatable objects. Iterators are a type of iterator and are more limited.
** ・ Iterable ** A repeatable object. Objects of type list, tapple, range.
"For i in iterable"
** ▼ Confirmation of iterator type **
For list
arr = [1,2,3,4,5]
iterArr = iter(arr)
type(iterArr)
#list_iterator
For tuple
brr = (1,2,3,4,5)
iterArr = iter(arr)
type(iterArr)
#tuple_iterator
For range
crr = range(5)
iterArr = iter(arr)
type(iterArr)
#range_iterator
** ・ next function ** Extract the elements of type iter one by one. irreversible.
next (iterator)
Iterator & next
arr = [1,2,3,4,5]
iterArr = iter(arr)
next(iterArr)
1
next(iterArr)
2
~
~
~
next(iterArr)
5
next(iterArr)
StopIteration: #← An error will occur if all are extracted
If you use an iterator and next, you can process in order.
▼ Iterators can also use for statements. Iterators are one of the iterator elements.
python
arr = [1,2,3]
iterArr = iter(arr)
for i in iterArr:
print(i)
1
2
3