Welcome, guest | Sign In | My Account | Store | Cart

I've often needed to take out or reorder the columns in a list of lists. I'm embarrased to say it took me a while to think of this, it's so simple, but I looked around and have not found any examples of it, so...

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 1, 2, 3
# 4, 5, 6
# 7, 8, 9
#Task: remove the middle column

temp = [[1,2,3],[4,5,6],[7,8,9]]
newTemp = [[x[0],x[2]] for x in temp]

#now newTemp is:
# 1, 3
# 4, 6
# 7, 9

I can't think why I've never seen this before; it strikes me as it belongs in the intro of list comprehensions. I looked through several books, and never saw anything refering to subscripting and list comprehensions. Perhaps I'm slow, or perhaps this is just one of those blind spots.

Created by Jason Whitlark on Fri, 28 Mar 2003 (PSF)
Python recipes (4591)
Jason Whitlark's recipes (4)
Python Cookbook Edition 2 (117)

Required Modules

  • (none specified)

Other Information and Tasks