Education, Learning, python, Strings, Technology

Unpack an iterable object to separate variables

# Unpack a Tuple of N-elements to a collection of  N-variables

x,y = (2,3)
print(x)
print(y)

## A more practical use
## Given a tuple of N-lists, you can use unpacking into variables

sharepricedata =  ([ 'Citi', 50, 91.1, (2012, 12, 21) ], [ 'JPMC', 50, 91.1, (2012, 12, 21) ])

for i in sharepricedata:
    name, shares, price, date = i
    print(name + ' ' + 'is priced at ' + str(price))

# Unpacking actually works with any object that happens to be iterable, not just tuples or lists.
# This includes strings, files, iterators, and generators.

# Alternatively you can pick a throw away variable name for values you want to discard
# If you want to discard date and shares

for i in sharepricedata:
    name, _, price, _ = i
    print(name + ' ' + 'is priced at ' + str(price))

 # unpacking iterable of Arbitrary length using *
 # Example discard all elements except first and last
for i in sharepricedata:
    name, *middle, (year,month,day) = i
    print(name + ' ' + 'is listed in year  ' + str(year))

 ## Scenario. Say you have different record types coming in  a file

allrecs = [
[1,22,'M','London'],
[1,22,'M','Manchester'],
[1,25,'M','London'],
[1,20,'M','Fleet'],
[2,'GU51 2US'],
[2,'GU51 2UF']
]

def rec1(x,y,z):
    print(str(x) + ' ' + y + ' ' + z)


def rec2(a):
    print(a)

for rectype,*args in allrecs :
    if rectype == 1:
        rec1(*args)
    else:
        rec2(*args)




Leave a comment