unpacking elements in python - any tips u want to share ?
Ganesh Pal
ganesh1pal at gmail.com
Thu Jul 27 10:33:14 EDT 2017
Hello Python friends ,
I need some inputs on the efficient way to unpack the elements in python ,
I know this is a very basic question , just curious to know if there are
better way ways to achieve it .
For our initial discussion let’s start with list
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
>>var1 = “”
>>var2 = “ ”
>>var 3 = “ ”
>> var 4= “”
>> var5 = “”
>> var 6 = “”
>>var7 =””
>>> my_list = []
>>> my_list.append(1)
>>> my_list.append(0xffe)
>>> my_list.append(2)
>>> my_list.append('4th element')
>>> my_list.append('5th element')
>>> my_list.append(2)
>>> my_list.append(0xffe)
>>> my_list
[1, 4094, 2, '4th element', '5th element', 2, 4094]
>>> if len(my_list) == 7 :
... var1,var2,var3,var4,var5,var6,var7 = my_list
... print var1,var2,var3,var4,var5,var6,var7
... var8 = get_eighth_element(var1,int(var2),int(var3))
….. my_list.append(var8)
….print my_list
1 4094 2 4th element 5th element 2 4094
1 4094 2 4th element 5th element 2 4094 01
In case of list , I can use slices too , to unpack the elements I am
interested in .
Example : say If I need to compare second and second last element in the
list, here is the simple code using slices,
>>my_list[]
1 4094 2 4th element 5th element 2 4094 01
>>> my_list[-2]
4094
>>> my_list[1]
4094
>>var1 = my_list[-2]
>> var 2 = my_list[1]
>>> if len(my_list) == 8:
... if my_list[-2] == my_list[1]:
... print "Test Passed"
... else:
... print "Test Failed"
...
Test Passed
what other ways to I have ( if at all) ? to unpack the elements in python
Regards,
Ganesh
More information about the Python-list
mailing list