Alex Rivera | Logout

How do I merge a 2D array in Python into one string with List Comprehension?

Asked 2008-09-19T17:21:53.570
23

List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.

Say, I have a 2D list:

li = [[0,1,2],[3,4,5],[6,7,8]]

I would like to merge this either into one long list

li2 = [0,1,2,3,4,5,6,7,8]

or into a string with separators:

s = "0,1,2,3,4,5,6,7,8"

Really, I'd like to know how to do both.

Edit
Report

1 Answer

6

My favorite, and the shortest one, is this:

li2 = sum(li, [])

and

s = ','.join(li2)

EDIT: use sum instead of reduce, (thanks Thomas Wouters!)

answered 2008-09-19T17:27:43.820

Your Answer