Why do i need to use the for loop twice? (Using a list of lists in a function)


#1


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

my code works but. why?? i cant understand why i need to use for twice :frowning:


n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
    results = []
    
    for numbers in lists:
        for number in numbers:
            results.append(number)
    return results

print flatten(n)


#2

The Main list contains other lists as item.
First for loop loops through items of main list (that is list only)
Second loop loops through items of inside lists.
For visualtion use this site.. www.pythontutor.com

You can do this problem without that extra loop.
Fact:
You can concatenate two or more lists using + operator,so one loop will be suffice.


#3

What if we don't know, if a next item of a list is a string, number or even a new list. How we can check it? I have tried to use an 'if' statement, but i have got an error, so i have used concatenating:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
    results = []
    print type(lists[0])=='list'
    for numbers in range(0, len(lists)):
        if type(lists[numbers]) == 'list':
            flatten(lists[numbers])
        else:
            results.append(lists[numbers])
    return results
print flatten(n)

#4

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