3

Let's say I have the following lists of objects:

lol = [['When was America discovered by Christopher Colombus?', ['1492', '1510', '1776', '1820'], '1492'], ['What is the name of the school that Harry Potter attends?', ['Hogwarts', 'Gryffindor', 'Voldemort', 'Magic School'], 'Hogwarts'], ['How many colors are there in the common depiction of the rainbow?', ['5', '7', '9', '11'], '7']

I'm trying to flatten the inner list (e.g. remove the brackets). The result would look like

['When was America discovered by Christopher Colombus?', '1492', '1510', '1776', '1820', '1492']

I have seen general solutions for flattening entire lists such as here:

Flattening a shallow list in Python

But I cannot figure out how to selectively flatten a single list within a larger list of lists.

Parseltongue
  • 10,245
  • 27
  • 85
  • 148

2 Answers2

1

I think you mean that you want not just the output you show, but the other two in your sample output as well. Here's how to do that:

lol = [['When was America discovered by Christopher Colombus?', ['1492', '1510', '1776', '1820'], '1492'], ['What is the name of the school that Harry Potter attends?', ['Hogwarts', 'Gryffindor', 'Voldemort', 'Magic School'], 'Hogwarts'], ['How many colors are there in the common depiction of the rainbow?', ['5', '7', '9', '11'], '7']]

r = []
for x in lol:
    r.append([x[0]] + x[1] + [x[2]])

for rr in r:
    print(rr)

Result:

['When was America discovered by Christopher Colombus?', '1492', '1510', '1776', '1820', '1492']
['What is the name of the school that Harry Potter attends?', 'Hogwarts', 'Gryffindor', 'Voldemort', 'Magic School', 'Hogwarts']
['How many colors are there in the common depiction of the rainbow?', '5', '7', '9', '11', '7']
CryptoFool
  • 17,917
  • 4
  • 23
  • 40
0

If you know how to flatten an entire list, and you want to know how to flatten just the first list, then you aren't really asking how to flatten a list, you are asking how to select the first item in a list, in which the answer is to do sublist=lol[0] and then apply the answers to the other questions to sublist.

Acccumulation
  • 3,215
  • 1
  • 6
  • 11