Python example to unpack tuple or sequence or iterable such that the tuple may be longer than N elements, causing a “too many values to unpack” exception.
1. Unpack tuple with arbitrary length
star expressions” can be used to to unpack tuples with arbitrary length.
>>> employee = ('Lokesh', 'firstname.lastname@example.org', '111-222-333', '444-555-666') >>> name, email, *phone_numbers = employee >>> name 'Lokesh' >>> email 'email@example.com' >>> phone_numbers ['111-222-333', '444-555-666']
>>> *elements, end = [1,2,3,4,5,6,7,8] >>> elements [1,2,3,4,5,6,7] >>> end 8
2. Unpack tuple and throw away unwanted values
Sometimes you might want to unpack values and throw them away. You can’t just specify a bare
* when unpacking, but you could use a common throwaway variable name, such as “_” or ignore.
>>> record = ('Lokesh', 37, 72.45, (1, 1, 1981)) >>> name, *_, (*_, year) = record #Only read name and year >>> name 'Lokesh' >>> year 1981
Happy Learning !!