Python Challenge - Flatten an Array

This community-built FAQ covers the “Flatten an Array” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Python challenge Flatten an Array

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hi,

This is the answer I got to this question:

def flatten_array(arr):
flattened =
for i in arr:
if isinstance(i, list) == True:
for a in i:
flattened.append(a)
else:
flattened.append(i)
return flattened

print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))

Just wondering if there are any other ways to solve this question at all? Be great to have some feedback :slight_smile:

3 Likes

I have done it almost the same way:

def flatten_array(arr): # Write your code here new_arr = [] for i in arr: if isinstance(i, list): new_arr += [x for x in i] else: new_arr.append(i) return new_arr print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
def flatten_array(arr): if not isinstance(arr, list): return [arr] return sum(list(map(flatten_array, arr)), []) print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))

Recursive. This one infinitely flattens. :slight_smile:

1 Like
def flatten_array(arr): lst = [] for a in arr: if type(a) == int: lst.append(a) elif type(a) == list: for i in a: lst.append(i) return lst print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))

That is almost the saem as my solution. First I was not sure if the lists were nested deeper. That would make the challenge even more interesting.

def flatten_array(arr): # Write your code here lists = [] for i in range(len(arr)): if type(arr[i]) != list: lists.append(arr[i]) else: for i2 in range(len(arr[i])): lists.append(arr[i][i2]) return lists print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
def flatten_array(l): new_list = [] for i in range (len(l)): if type(l[i]) != int: new_list.extend(l[i]) else: new_list.append(l[i]) return new_list list1 = [1, 2, [3, 4, 5], 6, [7, 8], 9] print(flatten_array(list1))

I hope this solution will help you :smiley:

def flatten_array(arr): ret = [] for i in arr: try: for j in i: ret.append(j) except: ret.append(i) return ret print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
1 Like

Another recursive version…

def flatten_array(arr):
  brr = []
  for x in arr:
    brr += flatten_array(x) if isinstance(x, list) else [x]
  return brr

print (flatten_array([1, 2, 3, [4, 5], 6, [7, 8], 9]))
def flatten_array(arr): # Write your code here z=[] for i in arr: if type(i)==int: z.append(i) else: for b in i: z.append(b) return z print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))

One might wish to consider the type of content we can store in a list. Technically we are not testing the contents for any type other than list.

(post deleted by author)

def flatten_array(arr): # Write your code here result = [] for i in arr: if type(i) != int: for j in i: result.append(j) else: result.append(i) return result print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))

Same comment as a couple of posts above… What if the array contains strings or some other numeric value like a float? The type of content is not important, only whether it is a list or not.

def flatten_array(arr): flatten = [] for i in arr: if type(i)==list: flatten.extend(flatten_array(i)) else: flatten.append(i) return flatten print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
def flatten_array(arr):
  # Write your code here
  flattened=[]
  for x in arr:
    try:
      for y in range(len(x)):
        flattened.append(x[y])
    except:
      flattened.append(x)
  return(flattened)

print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))

i like try/except for clarity.

Did this pass the tests? It shouldn’t have.

print(flatten_array([1, 2, [3, [4], 5], 6, [7, 8], 9]))

output

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

Hi, I got this error from running my code but I still managed to run the program and get correct output. Can someone explain why the code works but the tester doesn’t work?

“Tests failed to run due to an error: “‘int’ object is not iterable”. Check your code and try again.”

Here’s my code:

def flatten_array(arr):
  lst = []
  for i in arr:
    if len(str(i)) > 1:
      for j in i:
        lst.append(j)
    else:
        lst.append(i)
  return lst
print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))

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

Thank you!!

We’re flattening an array. We should not be type casting the values of the array.

>>> len(str([])) > 1
True
>>> 

N. B.

When we cast a list to a str the brackets are converted to printable characters, as are the int/float/bool, commas and white space.

>>> str([3, 4, 5])
'[3, 4, 5]'
>>> 
>>> len(str([3, 4, 5]))
9
>>> 
>>> str([3, 4, 5]).find('3')
1
>>> str([3, 4, 5]).find('4')
4
>>> str([3, 4, 5]).find('5')
7
>>>