Skip to content

Instantly share code, notes, and snippets.

@DevJulianSalas
Created February 6, 2018 16:32
Show Gist options
  • Save DevJulianSalas/3acc175f6b36617fc965b7b128a61027 to your computer and use it in GitHub Desktop.
Save DevJulianSalas/3acc175f6b36617fc965b7b128a61027 to your computer and use it in GitHub Desktop.
Unpacking tuples
"""
Reference Python cookbook
If you have tuples an awesome feature is unpacking from python, sometimes you need to unpacking tuples without know the index.
x,y,z = (1,2)
This raise an error about
ValueError: need more than 2 values to unpack
This is because you are unpacking more than values that expect.
Hint
* Unpacking object can be done with any Iterable object 'strings' 'list', 'files'
'iterators'
"""
#If you need to reject any value from tuple you can use common name variable for instance '_'
name, last_name, date, _ = ('David', 'Murch', 21, datetime(2000,11,11), 'nothing_special')
#Unpacking elements from iterables of arbitrary length
#For cases when you need reject or grouping common values for instance phone numbers you can use start expressions
user = ('Den', 'Lopez', +57312338012, +5732130812093, +5731234141, 'graded)
name, last_name, *phone_numbers, grade = user
#example 2, unpacking with start expresions
path_shadow_user = """ubuntu:$6$dEp7Pp5.$rWhN7RxUrkSQ1qew12312fvdsfuLAKk9WiuewT3M8CKzMriyzUlSJquyywwaURPabLEPGTDpQz2btx/xFbfXgR9qnEAVObc1:17562:0:99999:7:::"""
user, encryp_pass, uid, *_ = path_shadow_user.split(':')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment