Python Forum
concatenating lists in a comprehension
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
concatenating lists in a comprehension
#1
i have an iterator that yields a list each time it is iterated. i want to get all of its lists concatenated together as one big long list. easy enough, but, i want to do it in a comprehension and am coming up empty trying to code that.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
from itertools import chain
result = list(chain.from_iterable(generate_the_lists()))
Reply
#3
i was trying to come up with some way to construct it but i was unable to. this suggests there isn't such a simple way. i would have need to make a function ... or use this.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
You just do a double list comprehension. The trick to these is to do the for clauses 'backwards' to what you might think:

Output:
>>> data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> [item for row in data for item in row] [1, 2, 3, 4, 5, 6, 7, 8, 9]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  concatenating 2 items at a time in a python list K11 3 2,326 Oct-21-2020, 09:34 AM
Last Post: buran
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,368 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Concatenating strings in cgi Meera2019 2 1,897 Aug-31-2019, 05:57 PM
Last Post: Meera2019
  Using function argument in lists comprehension. blackknite 5 3,051 Apr-23-2019, 09:59 PM
Last Post: snippsat
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,264 Mar-20-2019, 08:01 PM
Last Post: stillsen
  concatenating list with tuple Skaperen 7 4,410 Sep-28-2018, 05:55 AM
Last Post: Skaperen
  joining a variable number of lists in a comprehension Skaperen 2 2,807 Oct-14-2017, 08:19 AM
Last Post: Skaperen
  How to create a long string by concatenating two lists nikhilkumar 11 7,528 Jul-12-2017, 05:36 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020