How do I write a list comprehension that flattens a list of lists in python?
- User
How do I write a list comprehension that flattens a list of lists in python?
Assistant
To flatten a list of lists in Python using list comprehension, you can use the following code:
codeflat_list = [item for sublist in original_list for item in sublist]This code creates a new list
flat_listthat contains all the items from the original list of listsoriginal_list. Thesublistvariable iterates over each sublist inoriginal_list, and theitemvariable iterates over each item in the sublist. This way, all the items from all the sublists are collected in theflat_list.Here is an example:
codeoriginal_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] flat_list = [item for sublist in original_list for item in sublist] print(flat_list)Output:
code
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.