Python array for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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)

10th Feb 2019, 6:03 PM
naomi - avatar
2 Answers
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 - avatar
+ 1
Know it's late but thank you!!!
2nd Mar 2019, 12:14 AM
naomi - avatar