-1

Consider this list of tuples:

my_list = [("a", "b"),("a", "b", "c"),("a",)]

Desirable outcome is:

my_list = ["ab", "abc","a"]

How can one achieve the result with minimal code?

All of my attempts have either lead to ineloquent block of code or have failed entirely as I can't find an easy way to replace the tuples with the strings within combined when the number of strings in the tuple is unknown.

nms1s
  • 1
  • 1
  • Does this answer your question? [Python convert tuple to string](https://stackoverflow.com/questions/19641579/python-convert-tuple-to-string) – mkrieger1 Dec 18 '20 at 22:32
  • 1
    `[''.join(t) for t in my_list]` – John Coleman Dec 18 '20 at 22:33
  • 2
    Not sure why not knowing the number of strings in a tuple poses a problem. Do you know that you can get the number of items in a tuple by using the `len` function? – mkrieger1 Dec 18 '20 at 22:34

4 Answers4

4

How about this?

my_list = [("a", "b"), ("a", "b", "c"), ("a",)]

my_list = ["".join(x) for x in my_list]

print(my_list)

Here is the result:

['ab', 'abc', 'a']
QQQ
  • 327
  • 1
  • 6
0
In [131]: my_list = [("a", "b"),("a", "b", "c"),("a",)]                         

In [132]: new_list = ["".join(a) for a in my_list]                              

In [133]: new_list                                                              
Out[133]: ['ab', 'abc', 'a']
Rajat Mishra
  • 3,635
  • 4
  • 27
  • 41
0

I'd suggest using str.join, for example in such a way:

new_list = list()        #Initialize output list

for item in my_list:     #Iterate through the original list and store the tuples in "item"
    el = ''.join(item)   #Store the concatenate string in "el"
    new_list.append(el)  #Append "el" to the output list "new_list"
J. M. Arnold
  • 6,261
  • 3
  • 20
  • 38
-1

One of the solution would be to use two for loops:

my_list = [("a", "b"), ("a", "b", "c"), ("a",)]
new_list = []
for tup in my_list:
    merge = ""
    for item in tup:
        merge += item
    new_list.append(merge)
print(new_list)
bvsh
  • 64
  • 6