-1

I want to create a function that takes a 2 dimensional list and outputs a 1 dimensional list with the same contents. Here is what I have:

twoDlist= [[23, 34, 67],[44,5,3],[7,8,9]]
def twoone (list1):
    for x in range(len(list1)):
        for y in range(len(list1)):
            list2=[]
            list2.append(list1[x][y])
print(twoone(twoDlist))

Only problem it returns 'None'. What is wrong, and how can I fix it?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
bahaaz
  • 45
  • 1
  • 3
  • 9

3 Answers3

2

Two issues here, the first is that you are not returning a value and the second is that you are resetting list2 to an empty list inside of your nested loop, so at the end you would only have a single element in it.

Here is how you could fix your code:

def twoone(list1):
    list2 = []
    for x in range(len(list1)):
        for y in range(len(list1)):
            list2.append(list1[x][y])
    return list2

>>> twoone(twoDlist)
[23, 34, 67, 44, 5, 3, 7, 8, 9]

However, there are much better ways to do this, see the link in jtbandes' comment.

The best way is itertools.chain():

>>> from itertools import chain
>>> list(chain.from_iterable(twoDlist))
[23, 34, 67, 44, 5, 3, 7, 8, 9]
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
2

The reason your method returns None is that it does not have a return statement. Even with a return statement, however, the result is incorrect. As other answers point out, initializing list2 outside the loops (and returning list2) solves the issue.

You could also use a nested list comprehension to accomplish the task more compactly.

def twoone(list1):
    return [val for lst in list1 for val in lst]
David Alber
  • 17,624
  • 6
  • 65
  • 71
0

The reason that its happening is that you are reinitialise list2 as [] in every iteration. Try initialising the list2 part outside the for loop in twoone.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175