# Iterating through tuples of varying sizes in a list

This is an exercise to find the smallest number out of three options. If an option doesn’t have exactly three option, then it should be skipped.

Why doesn’t the code below work. I thought that len() return an integer and would be able to compare it to a number of items in the tuple and be able to skip it.

xoxo

data = [
(3),
(7, 3, 5),
(15, 20, 40),
(300, 550, 137),
]

for i in range(len(data)):
if len(data[i]) = 3:
for num1, num2, num3 in data:
if num1 < num2:
if num1 < num3:
if num2 < num1:
if num2 < num3:
else:

That is not a tuple.

``````(3,)
``````

This is a tuple of the bare minimum.

Once we correct the tuple, this line will work so long as we use `==`, not `=`.

Given that we are not mutating the list, we don’t need indexes.

``````for x in data:
if len(x) == 3:
``````

Now this brings us to the elephant in the room: `data`, a list of tuples.

``````for num1, num2, num3 in data[i]:
``````

Below is a spoiler where we implement three built in functions, `map()`, `filter()` and `min()`

``````data = [
(3,),
(7, 3, 5),
(15, 20, 40),
(300, 550, 137),
]
def smallest_value(s):
return [*map(lambda x: min(x), filter(lambda x: len(x) == 3, s))]
``````
``````>>> smallest_value(data)
[3, 15, 137]
>>>
``````

Looping back…

Before the above code gets laughed out of the room, it seemed prudent to step back and examine that contraption. In an instant, it’s replacement came into being:

``````def smallest_value(s):
return [min(x) for x in s if len(x) == 3]

>>> data = [
(3,),
(7, 3, 5),
(15, 20, 40),
(300, 550, 137),
]
>>> smallest_value(data)
[3, 15, 137]
>>>
``````

D’oh! See how we can make things harder for one’s self when we think we’re being clever?

``````# here's our filter
for x in s if len(x) == 3
# and here is our map
[min(x) ... ]
``````

Still, the thing they (the two versions) both have in common is they are expressions, something we can return as a value. Either form can be traced back to the imperative form we naively produce at the outset (which is good).

If we start out trying to write clever expressions we end up facing review. If we start out writing imperative algorithms and code in general we have something as a basis to iron all the bugs out of, then step forward into transmuting or refactoring of working, simplified imperative code.

Obviously it makes no sense doing this in reverse, though it is highly doable. Care to try?