Tuple Sums (Solution)
00:00 Let’s start with creating the data tuple. I’m going to open and close parentheses, and then inside of here I can create two more tuples that are each going to contain two integers, so I’m making another set of parentheses, and then inside of that set of parentheses, I’m putting data just one and two.
00:19 Then I will put a comma after and then create the next element of the data tuple, which is another tuple. And then this one contains the integers three and four, separated by commas again, so we have
01:11 We’re going to need a for loop, but I want to keep track of the index of the data. So I’m going to start off by creating an index variable that I’ll start with one, and then I’m writing the for loop for each row in the data tuple, I want to print an f-string, so it’s just a nice way of formatting it.
and that’s going to take on the values of first, the first tuple, and then the second tuple. And summing all elements in each of those rows using, using this
sum() opening parentheses, and then passing in the loop variable row.
Okay, that should be the string that I want to print. Then I still need to increase the index. So I’m going to say
index += 1 so that then, it’s going to say row number two when it goes the second time through the loop, let’s try it out.
Note that there’s also another way of solving this using the built-in
enumerate() function. Maybe you’ve heard about it, maybe not. If not, and you’re happy with the solution that’s similar to the one before where you define an index variable, then that’s completely fine.
But I wanted to show you this
enumerate() function too, because it makes the code look a little more Pythonic. I would say. You can say for
, row in enumerate(data), and then I have to define that I want to start at one because otherwise it starts at zero by default.
Become a Member to join the conversation.