Skip to content Skip to sidebar Skip to footer

Unpacking Iterables In Python3?

Why is this returning in sort_tup_from_list for key, val in tup: ValueError: not enough values to unpack (expected 2, got 1) # list with tuples lst = [('1', '2'), ('3', '4')] # so

Solution 1:

Your second for loop is looping through items in the tuple, but you're grabbing both of the items in it. I think this is what you want:

# list with tuples
lst = [("1", "2"), ("3", "4")]

# sorting list by tuple val key
def sort_tup_from_list(input_list):
    tmp = []
    print(tmp)
    for key,val in input_list:
        tmp.append((val, key))
        tmp.sort(reverse=True)
    return tmp

print(sort_tup_from_list(lst))

Post a Comment for "Unpacking Iterables In Python3?"