Flatten a list inside list of tuples

Question:

I have the following list of tuples.

lst = 
    [
        ('LexisNexis', ['IT Services and IT Consulting ', ' New York City, NY']),
        ('AbacusNext', ['IT Services and IT Consulting ', ' La Jolla, California']), 
        ('Aderant', ['Software Development ', ' Atlanta, GA']),
        ('Anaqua', ['Software Development ', ' Boston, MA']),
        ('Thomson Reuters Elite', ['Software Development ', ' Eagan, Minnesota']),
        ('Litify', ['Software Development ', ' Brooklyn, New York'])
    ]

I want to flatten the lists in each tuple to be part of the tuples of lst.
I found this How do I make a flat list out of a list of lists? but have no idea how to make it adequate to my case.

Asked By: Joe

||

Answers:

You can use unpacking:

lst = [('LexisNexis', ['IT Services and IT Consulting ', ' New York City, NY']),
       ('AbacusNext', ['IT Services and IT Consulting ', ' La Jolla, California']), 
       ('Aderant', ['Software Development ', ' Atlanta, GA']),
       ('Anaqua', ['Software Development ', ' Boston, MA']),
       ('Thomson Reuters Elite', ['Software Development ', ' Eagan, Minnesota']),
       ('Litify', ['Software Development ', ' Brooklyn, New York'])]

output = [(x, *l) for (x, l) in lst]

print(output)
# [('LexisNexis', 'IT Services and IT Consulting ', ' New York City, NY'),
#  ('AbacusNext', 'IT Services and IT Consulting ', ' La Jolla, California'),
#  ('Aderant', 'Software Development ', ' Atlanta, GA'),
#  ('Anaqua', 'Software Development ', ' Boston, MA'),
#  ('Thomson Reuters Elite', 'Software Development ', ' Eagan, Minnesota'),
#  ('Litify', 'Software Development ', ' Brooklyn, New York')]
Answered By: j1-lee

I’ve found the answer by Deacon using abc from collections. It is worth to try it too.

from collections import abc

def flatten(obj):
    for o in obj:
        # Flatten any iterable class except for strings.
        if isinstance(o, abc.Iterable) and not isinstance(o, str):
            yield from flatten(o)
        else:
            yield o

[tuple(flatten(i)) for i in lst]
Out[47]: 
[('LexisNexis', 'IT Services and IT Consulting ', ' New York City, NY'),
 ('AbacusNext', 'IT Services and IT Consulting ', ' La Jolla, California'),
 ('Aderant', 'Software Development ', ' Atlanta, GA'),
 ('Anaqua', 'Software Development ', ' Boston, MA'),
 ('Thomson Reuters Elite', 'Software Development ', ' Eagan, Minnesota'),
 ('Litify', 'Software Development ', ' Brooklyn, New York')]
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.