0

I'm feeling extra dumb tonight. If I have a basic multi-dimensional list:

my_list = [['Bob', 43, 'Tall', 'Green'],
           ['Sally', 32, 'Short', 'Blue'],
           ['Tom', 54,'Medium','Orange']]

I can easily use a list comprehension to grab the first column:

new_list = [row[0] for row in my_list]

or I can grab 3 columns:

new_list = [row[0:3] for row in my_list]

but how would I grab columns 1 and 3 only?

new_list = [row[0,2] for row in my_list]

if not with a list comprehension, then how to accomplish with the least amount of code?

4 Answers 4

2

One way:

new_list = [[row[0], row[2]] for row in my_list]

In this approach you're constructing a new list yourself for each row and you're putting element 0 and 2 in there as elements.

Sign up to request clarification or add additional context in comments.

Comments

1
import operator

In [7]: answer = [operator.itemgetter(0,2)(s) for s in my_list]

In [8]: answer
Out[8]: [('Bob', 'Tall'), ('Sally', 'Short'), ('Tom', 'Medium')]

Comments

1

While you can certainly use itemgetter - which you don't need to assign to a variable, nor do you need to fully qualify its name:

from operator import itemgetter
[itemgetter(0,2)(row) for row in my_list]

You could also just do what itemgetter does, which in this case would mean a nested list comprehension inside your list comprehension:

[[row[i] for i in [0,2]] for row in my_list]

Comments

0

In addition to what @Simeon Visser wrote, you could also use itemgetter:

my_list = [['Bob', 43, 'Tall', 'Green'],
           ['Sally', 32, 'Short', 'Blue'],
           ['Tom', 54,'Medium','Orange']]

from operator import itemgetter

itg = itemgetter(0,2)

print([itg(row) for row in my_list])

Gives:

[('Bob', 'Tall'), ('Sally', 'Short'), ('Tom', 'Medium')]

1 Comment

@PadraicCunningham Thx. Haven't noticed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.