For that print statement one expects it would be print x
, so it will echo, [4, 5, 5] and [1, 3], successively.
int(y)
that line is not a statement so does nothing. It’s moot that y is already an integer. If it were not, what would we prove by casting it to one? It will affect the end product.
There is the problem. return
is inside the outer loop so never gets to the second sequence.
>>> def product(sequence):
result = 1
for x in sequence:
print (x)
for y in x:
print (y)
result *= y
return result
>>> product([[4, 5, 5], [1,3]])
[4, 5, 5]
4
5
5
[1, 3]
1
3
300
>>>
Aside
The above function is trapped in a bubble in terms of re-usability since it is confined (fixed) to a list of lists. What happens if we pass in a single list with no nested members?
>>> product([4, 5, 5, 1, 3])
4
Traceback (most recent call last):
File "<pyshell#82>", line 1, in <module>
product([4, 5, 5, 1, 3])
File "<pyshell#77>", line 5, in product
for y in x:
TypeError: 'int' object is not iterable
>>>
Or a list with nested lists that are also nested lists?
>>> product([[4, [5, 5]], [1, [3]]])
[4, [5, 5]]
4
[5, 5]
[1, [3]]
1
[3]
Traceback (most recent call last):
File "<pyshell#83>", line 1, in <module>
product([[4, [5, 5]], [1,[3]]])
File "<pyshell#77>", line 7, in product
result *= y
TypeError: can't multiply sequence by non-int of type 'list'
>>>
The parameter name is somewhat misleading since we first think of a sequence as being a flat list. A minor point, though.
How can we make this function more flexible and re-usable in all sorts of situations? Since we want the product of all the numbers in the list(s) then it makes sense to consider flattening the list.
That may be a new concept, as well as the consideration of how expensive nested lists are in terms of time complexity (Big-O, for later study). List flattening is the process of breaking all the values out of their respective lists into a single, flat list.
>>> def flatten(s):
if type(s) != list: raise TypeError
if s == []: return s
if type(s[0]) == list:
return flatten(s[0]) + flatten(s[1:])
return s[:1] + flatten(s[1:])
>>> flatten([[4, [5, 5]], [1,[3]]])
[4, 5, 5, 1, 3]
>>> flatten([[4, [5, 5], 4, [5, [4, 5]], [1, [3], [1, [1, [1, 3]]]]]])
[4, 5, 5, 4, 5, 4, 5, 1, 3, 1, 1, 1, 3]
>>>
No, this is not something you are expected to know or even understand. It’s a function that uses recursion to drill down into all the nested layers, gradually reducing the input to a flattened list. List slicing and recursion will come up in your learning but I don’t believe it is covered in the Python 2 track (I’ve been wrong, before).
Add all this to your extra study list and take it up when you’ve got far enough along.
So now that we have a function to flatten lists,
>>> def product(data):
sequence = flatten(data) # dependency
result = 1
for x in sequence:
result *= x
return result
>>> product([[4, [5, 5], 4, [5, [4, 5]], [1,[3], [1, [1, [1, 3]]]]]])
360000
>>>