unpacking elements in python - any tips u want to share ?
Stephan Houben
stephanh42 at gmail.com
Sun Aug 6 03:45:51 EDT 2017
Hi Ganesh,
Op 2017-07-27, Ganesh Pal schreef <ganesh1pal at gmail.com>:
> I have a list with say 7 elements say if I need to unpack first 3
> elements in the list and pass it an argument to the new fuction, here is
> my elementary code
One way to do exactly what you request here is:
new_function(*my_list[:3])
Explanation:
1. my_list[:3] produces a list of the first 3 elements of my_list
2. new_function(*some_sequence)
(Note the * in the calling syntax!)
is equivalent to calling new_function with all the elements of
some_sequence individually:
new_function(some_sequence[0], some_sequence[1], ...)
But I observe that this is slightly different from the code you
actually present:
> ... var1,var2,var3,var4,var5,var6,var7 = my_list
> ... var8 = get_eighth_element(var1,int(var2),int(var3))
This code actually converts var2 and var3 into an integer first.
(By calling int).
Short intermezzo: I notice that you are apparently using Python 2,
because of this code:
> ….print my_list
This code would be print(my_list) in Python 3.
If you are just learning Python and there is no particular reason you
need Python 2, I would recommend Python 3 at this point. Python 2 is
still supported but only until 2020 so you may want to invest in
something more future-proof.
Anyway, the reason I bring it up is because in Python 3 you can do:
var1,var2,var3,*_ = my_list
var8 = get_eighth_element(var1,int(var2),int(var3))
This will work for any my_list which has at least 3 elements.
The syntax *_ binds the rest of the list to the variable _.
_ is a conventional name for a variable in which value you are not
interested.
If backward-compatibility with Python 2 is important, you can do instead:
var1,var2,var3 = my_list[:3]
var8 = get_eighth_element(var1,int(var2),int(var3))
Finally, I would want to point out that if these fields of the list
have some specific meaning (e.g. my_list[0] is first name, my_list[1]
is last name, my_list[2] is address, etc..), then a more idiomatic
Python solution would be to define a class with named members for these
things:
class Person:
def __init__(self, first_name, last_name, address, city):
self.first_name = first_name
self.last_name = last_name
self.address = address
self.city = city
Greetings,
Stephan
More information about the Python-list
mailing list