-2

I have written a program and I want the output to be: [5,1,2,3,4]

Can anybody tell me how to do this conversion? Coz my output is this for now==>> [5, [1, 2, 3, 4]]

4 Answers4

1

What is your input ???

I guess it look like: a = [5, [1, 2, 3, 4]]

And this is my solution

a = [5, [1, 2, 3, 4]]
tmp = []
for x in a:
    if isinstance(x, list):
        for y in x:
            tmp.append(y)
    else:
        tmp.append(x)
print(tmp)
DungPB
  • 56
  • 4
0
a = [5, [1, 2, 3, 4]]
print([a[0]]+a[1])

Simple question, you may combine two array together to form an new array. We only need to extract part of array and combine them to solve this problem.

The blank
  • 84
  • 6
0

You might try something like this.

a = [5, [1, 2, 3, 4]]

new_arr = []
for i in a:
    try: #If not an array, goes to except and appends integer
        for j in i: #Loops through elements in array
            new_arr.append(j)
    except:
        new_arr.append(i)

print(new_arr)
0

A more functional approach can be:

>>> a = [5, [1, 2, 3, 4]]
>>> f = lambda x : x if type(x) == list else [x]
>>> [elem for l in a for elem in f(l)]
[5, 1, 2, 3, 4]
Matias Lopez
  • 94
  • 1
  • 7