+ 1

Python array for loop

Came across this for loop in a python challenge. I'm still trying to understand exactly what it's doing. Any help? arr = [(5,8,0), (2,4)] sum = [] for x, *y in arr: sum = sum + y print(sum) https://code.sololearn.com/cP570hyz249g/?ref=app

10th Feb 2019, 6:03 PM
naomi
naomi - avatar
2 Answers
0
A for loop runs over the primary elements of a container. So if you wrote: for x in arr: x would be first a tuple of three, then a tuple of two, since that are the primary elements. x, *y now 'unpacks' that primary element, so that you can use the parts in every iteration as x and y. x will be the first element, and * in this context means: 'Stuff all the rest into a list named y!' So in first iteration you can use 5 and [8, 0] with x and y, in second iteration 2 and [4]. And since you can add up lists, you get a new list with everything but the first elements.
10th Feb 2019, 6:23 PM
HonFu
HonFu - avatar
+ 1
Know it's late but thank you!!!
2nd Mar 2019, 12:14 AM
naomi
naomi - avatar