Slice List of Lists in Python

Slicing a list of lists in Python can be done in three main ways:

  • Method 1: Using list comprehension,
  • Method 2: Using for-loop and,
  • Method 3: Using NumPy

Let’s go through them.

Method 1: Using List Comprehension

This approach allows us to slice the main list and the sublists even if the sublists are not of the same length.

The general syntax for list comprehension for slicing is given in the Figure below.

Here are some examples in code.

Output:

lst2:  [[56, 'SA'], [77, 'Poland']]
lst3:  [['Sam', 96, 'Warsaw'], ['Belinda', 78, 'Israel'], ['Sally', 56, 'SA'], ['Smith', 77, 'Poland']]
lst4:  [['Warsaw', None], ['Israel', 'GT'], ['SA', 'SL']]

Method 2: Using for-loop

This method iterates through sublists on the main lists and elements within the sublist and picks the selected elements.

Here is an example of picking the first three elements for each second and the third sublist.

Output:

[['Belinda', 78, 'Israel'], ['Sally', 56, 'SA']]

Method 3: Using NumPy

This is a very efficient method if your sublists are the same length. The following Figure shows the general syntax for slicing a list of lists in Python using NumPy.

Here are some examples of implementing slicing with NumPy

Output:

lst2:  [['Sam', 96], ['Belinda', 78], ['Sally', 56], ['Smith', 77]]
lst3:  [['Israel', 'GT'], ['SA', 'SL']]

Conclusion

This article discussed three methods for slicing nested lists in Python. The list comprehension and for-loop methods work for a nested list with sublists of different lengths, but the NumPy method needs sublists to be of the same sizes.