0

I want to concatenate an array inside another array.

Input = [['a', 'b'], ['c', 'd']]

Output: ['ab', 'cd']

Input = [['a', 'b'], ['c', 'd'], ['f', '.']]

Output: ['ab', 'cd', 'f.']

Conditions:

  • All arrays are string arrays
  • The array's length can be any value
  • At the end, I should have just one array, not array of arrays
2
  • What difficulty are you having writing a loop and creating a new list? Do you know how to join strings in a single list into a single string? Also unclear if you want to modify the input list or return a new one Commented Feb 15, 2021 at 17:58
  • Off-topic: Note that in Python, those are called lists not arrays. Commented Feb 15, 2021 at 18:32

3 Answers 3

2

Don't be decourage as a beginner, asking the right question in SO is rly diffcult - here is a simple list comprehension solution with a string join:

input = [["a","b"], ['c','d']]

[''.join(list) for list in input]

Output: ['ab', 'cd']

As suggested by @ChaddRobertson here is the same solution with an easier to understandable for-each loop:

ouput_list = []
for list in input:
    ouput_list.append(''.join(list))
    
print(ouput_list)
Sign up to request clarification or add additional context in comments.

7 Comments

List comprehension might not be the best method if somebody is just starting out - perhaps include a traditional loop in your answer, as they are often easier to visualize.
You are right - I also added a solution with a foreach loop
Nice answer but try to avoid naming variables after data types and built ins - list
... The downvote arrow says "This question does not show any research effort", which this one clearly does not (see How much research effort is expected of Stack Overflow users?). Encouraging, upvoting and answering questions that break rules and turn this site into "do my job for me" is a problem, even if those questions are asked by new users.
@PranavHosangadi - I think this quite a bit of bias on your part; you used SO for 10 years - you know the ins and outs of SO; As a Newbie you don't rly know the mentioned link in your 1st comment (except the tour) - SO also doesn't show then too you if you post your 1st question, therefore how should he know that in his first question? I thought it a reasonable question this is also why I upvoted the question from -1 to 0. ...
|
0

You could use map to apply a join to all the sublists:

[*map(''.join,Input)]


['ab', 'cd']

Comments

0
L = [["a", "b", "c"],["c","d"], ["x", "y", "z"]]

newL = []

for i in L:
    newL.append("".join(i))

print(newL)

This is what you need for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.