ezib
ezib

Reputation: 49

Slice list of lists without numpy

In Python, how could I slice my list of lists and get a sub list of lists without numpy?

For example, get a list of lists from A[1][1] to A[2][2] and store it in B:

A = [[1,  2,  3,  4 ],
     [11, 12, 13, 14],
     [21, 22, 23, 24],
     [31, 32, 33, 34]]

B = [[12, 13],
     [22, 23]]

Upvotes: 3

Views: 2507

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48100

You may also perform nested list slicing using map() function as:

B = map(lambda x: x[1:3], A[1:3])
# Value of B: [[12, 13], [22, 23]]

where A is the list mentioned in the question.

Upvotes: 0

alecxe
alecxe

Reputation: 474131

You can slice A and its sublists:

In [1]: A = [[1,  2,  3,  4 ],
   ...:      [11, 12, 13, 14],
   ...:      [21, 22, 23, 24],
   ...:      [31, 32, 33, 34]]

In [2]: B = [l[1:3] for l in A[1:3]]

In [3]: B
Out[3]: [[12, 13], [22, 23]]

Upvotes: 7

Related Questions