Unpacking Operator in Python
Description
In Python, unpacking refers to separating the elements inside an object individually. It is used by prefixing the object with *. For a useful example, suppose you want to run a for loop over indices 0 through 4 and 8 through 13. You might want to write code like for i in (range(5) + range(8, 14)), but a binary operation between the two range objects is not defined. In this case, you can use the unpacking operator * to expand the elements of each range into a new list, as shown below.
In Julia, this is called the splat operator and is used by appending ....
>>> for i in [*range(5), *range(8, 14)]:
... print(i)
...
0
1
2
3
4
8
9
10
11
12
13
Of course, you can implement this in other ways. You could handle exceptions explicitly or use multiple for loops. However, using the unpacking operator keeps the code concise and improves readability even when there are just two range objects, and when there are three or more, it’s not even worth comparing.
# 예외처리
for i in range(14):
if i < 5 or i >= 8:
print(i)
# 다중 for문
for r in (range(5), range(8, 14)):
for i in range(len(r)):
print(r[i])
Environment
- OS: Windows 11
- Python: 3.10.11
