18/18 Iterate through a list of indices?


Hi, I am trying to solve this using only method 2 to iterate. I've been able to iterate by list and then iterate by index, but how do I iterate using indices only?

def flatten(lists):
    results = []
    for items in lists:
        for i in range(len(items)):
            print items[i]
    return results
print flatten(n)

What I am trying to do:

def flatten(lists):
    results = []
    for i in range(len(lists)):
        for i in range(len(lists[i])):
            print lists[i]
    return results
print flatten(n)

Is this possible to do? Would someone mind explaining 'IndexError: list index out of range'? Thanks; very much appreciated.


I used (results += numbers ) instead of .append. The latest doesn't seem to work.


Hi there @talin_jayce_wauchope and @azizsa ,

You can solve the problem using indexes. But you must use a different index for the outer list and the inner lists.

Here's an example that uses index i for the outer list and index j for the inner lists:

def flatten(lists):
    results = []
    for i in range(len(lists)):
        for j in range(len(lists[i])):
    return results
print flatten([[1, 2, 3], [4, 5, 6, 7]])


[1, 2, 3, 4, 5, 6, 7]


I did it as below. Maybe we can compare each others' answer.

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

print flatten(n)


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


how do two indexes work together? in "results.append(lists[i][j]) "


This is the simplest way to run this code. Why should we use method 2 ever? All those range(len()) etc... I dont understand, why we would use such more complicated way if we can use what @medouxa just did.


My mistake was putting result = result.append(numbers)


thanks..it's simple and fast...clean code...:grin: