Using a list of lists in a function


#1

I can't understand what is going wrong, it's pretty confusing. Anyone have any ideas to make this easier to understand?
It's printing out: [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

Add your function here

def flatten(lists):
results = []
for item in lists:
for numbers in lists:
results.append(numbers)
return results

print flatten(n)


#2

Here:

    for item in lists:
        for numbers in lists:
            results.append(numbers)

The issue is in your second for loop (i.e. for numbers in lists). You already looped through lists, why loop through it again? You should be looping through item this time.


#3

I'm also stuck here. I am not sure what the problem is.

n = [3, 5, 7]

def total(numbers):
    result = 0
    for i in numbers:
        result = result + numbers[i]
    return result
    
print total(n)

I get this error:
Traceback (most recent call last):
File "python", line 9, in
File "python", line 6, in total
IndexError: list index out of range


#4

hey
try result = result + i.
you are already using for loop for each item so u dont have to add index when u add.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.