0

I have a list of let's say [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]] and its name is somelist. I want to do somelist[:2][:2] and have that return [[1,2], [1,2]]. So it slices the list and then slices that list and returns that. Is it even possible to do this in one line in python?

2
  • Sure, it possible in one line, but the syntax you're trying to use specifies the first two elements in the list, then the first two elements again; you want a slice on each of the members. Anyway, this belongs on SO and will be migrated shortly. Commented Jun 26, 2011 at 0:15
  • ...or somebody might just answer it here. You never know. Commented Jun 26, 2011 at 0:28

3 Answers 3

8

You can do this using list comprehension. I changed your sample input to make it clearer what is being selected:

>>> l = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> print [x[:2] for x in l[:2]]
[[1, 2], [5, 6]]
Sign up to request clarification or add additional context in comments.

Comments

1

Multidimensional slicing is easy with numpy:

import numpy
a = numpy.array([[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]])
print(a[:2,:2])

Comments

0

Are your lists always 16 elements in a 4x4 matrix? If you are simply trying to get the 4 lower right corner elements, try:

>>> l =  [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
>>> print [l[2][:2], l[3][:2]]
[[1, 2], [1, 2]]

Otherwise, for a general solution the list comprehension mentioned by others is better.

It would be interesting to benchmark both and see which is faster for your use case. Though this sounds like premature optimization to me.

Comments

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.