I have arrays 'a', 'b' and 'c'. I want to create the array 'd' using concatenate()
and add a, b or c if they exist.
d = concatenate([a (if a exists),b (if b exists),c (if c exists)])
Try this. If you want your d is a list of list.
a = []
b = ["B", "C"]
c = ["A", "C", "D"]
def concatenate(*args):
return [item for item in args if item]
print(concatenate(a,b,c))
OUTPUT:
[['B', 'C'], ['A', 'C', 'D']]
But if you want just the values of a,b,c in to d:
a = []
b = ["B", "C"]
c = ["A", "C", "D"]
def concatenate(*args):
return [item for arr in args for item in arr]
print(concatenate(a,b,c))
OUTPUT:
['B', 'C', 'A', 'C', 'D']
The *args
is for your function to accept multiple arguments/lists.
INPUT:
a = []
b = ["B", "C"]
c = ["A", "C", "D"]
d = ["X", "Z", "E"]
e = ["J", "H", "G"]
f = ["K", "L", "D"]
concatenate(a,b,c,d,e,f)
OUTPUT:
['B', 'C', 'A', 'C', 'D', 'X', 'Z', 'E', 'J', 'H', 'G', 'K', 'L', 'D']