Print specific items in a List of Lists in Python

avatar

Borislav Hadzhiev

Last updated: Sep 11, 2022

banner

Photo from Unsplash

Print specific items in a list of lists in Python #

Access the sublist items at a given index to print specific items in a list of lists. You can use a for loop to iterate over the list and print only the items for which a condition is met.

main.py
list_of_lists = [ ['bobby', 'hadz', 'com'], ['a', 'b', 'c'], ['d', 'e', 'f'] ] print(list_of_lists[0][0]) # 👉️ 'bobby' print(list_of_lists[0][1]) # 👉️ 'hadz' for sublist in list_of_lists: # bobby com # a c # d f print(sublist[0], sublist[-1]) for sublist in list_of_lists: for item in sublist: if 'b' in item: # bobby # b print(item)

If you need to access a specific item in a list of lists, use two sets of square brackets.

main.py
list_of_lists = [ ['bobby', 'hadz', 'com'], ['a', 'b', 'c'], ['d', 'e', 'f'] ] print(list_of_lists[0][0]) # 👉️ 'bobby' print(list_of_lists[0][1]) # 👉️ 'hadz' print(list_of_lists[2][-1]) # 👉️ 'f'

The first set of square brackets is used to select a sublist in the list.

The second set is used to select a specific item in the sublist.

You can also use list slicing.

main.py
list_of_lists = [ ['bobby', 'hadz', 'com'], ['a', 'b', 'c'], ['d', 'e', 'f'] ] print(list_of_lists[0][0:2]) # 👉️ ['bobby', 'hadz']

The syntax for list slicing is my_list[start:stop:step].

The start index is inclusive and the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

You can use a for loop if you need to iterate over the outer loop and print specific items in the sublists.

main.py
list_of_lists = [ ['bobby', 'hadz', 'com'], ['a', 'b', 'c'], ['d', 'e', 'f'] ] for sublist in list_of_lists: # bobby com # a c # d f print(sublist[0], sublist[-1])

Negative indices can be used to count backwards, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second-to-last item.

You can use a nested for loop if you need to iterate over each sublist and check for a condition.

main.py
list_of_lists = [ ['bobby', 'hadz', 'com'], ['a', 'b', 'c'], ['d', 'e', 'f'] ] for sublist in list_of_lists: for item in sublist: if 'b' in item: # bobby # b print(item)

The nested for loop iterates over the nested lists.

On each iteration, we check if the letter b is contained in the list item and if the condition is met, we print the item.

Here is an example that checks for a condition in a list of lists containing numbers and prints the matching elements.

main.py
list_of_lists = [ [1, 2, 3, ], [4, 5, 6], [7, 8, 9] ] for sublist in list_of_lists: for item in sublist: if item > 7: # 8 # 9 print(item)
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.