Exercise 18.. missing something basic


#1

Hi all,

I'm new to coding and python is the first course I'm working through from beginning to end.

I'm working on exercise 18 "Using a list of lists in a function"

https://www.codecademy.com/courses/python-beginner-nzzVa/4/2?curriculum_id=4f89dab3d788890003000096#

The aim is to create a function called flatten that takes a single list and concatenates all the sublists that are part of it into a single list.

I receive the following error message when trying to run the code below:
Traceback (most recent call last):
File "python", line 28, in
File "python", line 21, in flatten
TypeError: 'int' object is not iterable

Am I trying to apply something here that just is not suited to the task? Is the original solution viable, or is some variation of the second solution better, and why?


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

"""If I use the code below, I can complete the exercise. 
However, I want to use a range as we have been doing throughout this course. 
As I understand it, it's a better approach to use.

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

print flatten(n)

"""

#the code below here is what I am trying to get to work, but it doesn't work.
def flatten(lists):
    results = []
    for numbers in range(len(lists)):
        for items in numbers:
            results.append(items)
    print results
    return results



print flatten(n)


#2

Consider what that means and where you could be doing that in your code. And once you've found where you'll need to consider what you meant to do there, perhaps you mixed up some variables, perhaps you meant to do some other operation.

As for whether it's viable, that's something that you don't need any programming knowledge to determine. If you can imagine the steps in sufficient detail and you're convinced that they can be executed, then it can be, assuming you got your concept right.

You might not know what every single thing does in code, or what matches your concept. The solution to that is to observe what the code does and/or to look up how to do the action you want done or how the thing you are using behaves (documentation)

You might not know how to do all of the things I describe, but you need to decide which of them you're doing right now, and just as with everything, then find out how to do it, by using a search engine or when that fails, by asking.


#3

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