
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print All Sublists of a List in Python
Printing sublists in Python
The sublist is a portion of the list that contains one or more elements from the original list. These sublists can be contiguous(elements appear in the same order) or non-contiguous(where elements are taken from different positions).
Example: Printing all Contiguous Sublists
Let's look at the following example, where we are going to print all the contiguous sublists of the given list using nested loops.
def demo(a): for i in range(len(a)): for j in range(i, len(a)): print(a[i:j+1]) x = [11,2,3] demo(x)
The output of the above program is as follows -
[11] [11, 2] [11, 2, 3] [2] [2, 3] [3]
Example: Printing all non-contiguous sublists
In the following example, we are going to print all the non-contiguous sublists of the given list.
from itertools import combinations def demo(x): for r in range(1, len(x) + 1): for a in combinations(x, r): print(list(a)) demo([11,3,22])
The output of the above program is as follows -
[11] [3] [22] [11, 3] [11, 22] [3, 22] [11, 3, 22]
Printing sublists using List Comprehension
The python List comprehension offers a simple way to create a list using a single line of code. It combines loops and conditional statements.
Following is the syntax of Python list comprehension -
newlist = [expression for item in iterable if condition == True]
Example
Consider the following example, where we are going to print all the contiguous sublists using the list comprehension.
def demo(a): return [a[i:j+1] for i in range(len(a)) for j in range(i, len(a))] print(demo(['a', 'b', 'c']))
The output of the above program is as follows -
[['a'], ['a', 'b'], ['a', 'b', 'c'], ['b'], ['b', 'c'], ['c']]