Last Updated : 06 Dec, 2024
The unpacking techniques you use with lists also apply to python arrays, but with slight differences due to the nature of the array module. In this article, we'll explore how to unpack arrays using the array module in Python, and demonstrate various methods of unpacking.
Basic Array UnpackingTo begin with, let's see how we can unpack values from an array using the array module.
Python
import array
arr = array.array('i', [10, 20, 30])
a, b, c = arr
print(a)
print(b)
print(c)
Explanation:
Let's explore other methods unpacking an array in python:
Unpacking with Asterisk (*) OperatorUsing the * operator for unpacking works similarly with arrays as it does with lists. This allows you to capture multiple values in the middle of an array.
Python
import array
arr = array.array('i', [1, 2, 3, 4, 5])
a, *rest, e = arr
print(a) # 1
print(rest) # [2, 3, 4]
print(e) # 5
Explanation:
Arrays in Python can also contain other arrays, allowing you to work with nested structures. You can unpack nested arrays using a similar technique to unpacking simple arrays.
Python
import array
arr1 = array.array('i', [1, 2])
arr2 = array.array('i', [3, 4])
arr3 = [arr1, arr2]
(a, b), (c, d) = arr3
print(a, b) # 1 2
print(c, d) # 3 4
Explanation:
You can also slice an array and unpack the results. This can be particularly useful if you want to extract only specific parts of an array.
Python
import array
arr = array.array('i', [10, 20, 30, 40, 50])
first_two, *rest = arr[:2], arr[2:]
print(first_two) # [10, 20]
print(rest) # [30, 40, 50]
array('i', [10, 20]) [array('i', [30, 40, 50])]
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4