-1

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.

Joe
  • 575
  • 6
  • 24
  • So you will need the output as a list of tuples, without the list in the tuples? –  Aug 19 '22 at 02:06

2 Answers2

5

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')]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
1

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')]