-5

I would like to know how i can iterate through a list containing lists in python, however i would like to use the for loop method that uses index rather than iterating the normal way in python. is it possible to do that?

here is the python code:

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

def flatten(my_lists):
  results = []
  for outer in range(len(my_lists)):
    for inner in range(len(outer)):
      results.append(lists[outer][inner])
  return results

print flatten(n)

this is the error I get in the console:

Traceback (most recent call last):
  File "python", line 10, in <module>
  File "python", line 6, in flatten
TypeError: object of type 'int' has no len()

what is the error in my code ?

thanks in advance.

mlawati
  • 9
  • 1
  • 2

3 Answers3

3

outer and inner are both ints. Thus, len(outer) is bound to fail:

results = []
  for outer in range(len(my_lists)):
    # you need the length of the list in position 'outer', not of 'outer' itself
    for inner in range(len(my_lists[outer])):  
      results.append(my_lists[outer][inner])
  return results

It is easier not to use indexes at all:

results = []
  for lst in my_lists:
    for x in lst:  
      results.append(x)
    # Or without inner loop
    # results.extend(lst)
  return results

Moreover, for flattening a list of lists, there are many well-documented approaches, a straightforward one being a nested comprehension like:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
flat = [x for lst in n for x in lst]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

For more, you can refer to Making a flat list out of list of lists in Python and Flatten (an irregular) list of lists.

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Here the loop with indexes using enumerate.

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

def flatten(my_lists):
  results = []
  for idx, outer in enumerate(my_lists):
    for idx2, inner in enumerate(outer):
      results.append(my_lists[idx][idx2])
  return results

print flatten(n)

idx and idx2 are the current index of the for loops

Baart
  • 571
  • 1
  • 6
  • 19
0

In addition to the other answers, there is the standard library solution using itertools.

>>> import itertools
>>> n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
>>> print(list(itertools.chain(*n)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Or (possibly) more explicitly

>>> from itertools import chain
>>> n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
>>> print(list(chain.from_iterable(n)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

If you just need the flattened 'list' to be iterable, you can omit the list call and use the returned itertools.chain object.

>>> chain.from_iterable(n)
<itertools.chain object at 0x7f2ecc05f668>
Holloway
  • 6,412
  • 1
  • 26
  • 33