18/18 Iterate through a list of indices?


#1

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]
            results.append(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]
            results.append(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.


#2

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


#3

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])):
            results.append(lists[i][j])
    return results
    
print flatten([[1, 2, 3], [4, 5, 6, 7]])

Output:

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

#4

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:
           results.append(numbers)
    return results



print flatten(n)

result

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

#5

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


#6

Wow!
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.


#7

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


#8

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