Python @ DjangoSpin

PyPro #49 All Sublists of a List

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

All sublists of a list in Python

All sublists of a list in Python

All Sublists of a List: Write a Python program to obtain all possible sublists of a list, like mathematical sets. For example, list [1,2,3] contains the sublists [ [], [1], [1,2], [1,2,3], [2], [2,3], [3] ]. Keep in mind that an empty list is also one of the sublists of every list, like in mathematical sets.

all sublists of a list

listOne = [1,2,3,4]

subLists = [ [] ]			# initializing a list of sublists with an empty list

for lowerBoundOfSlice in range(len(listOne)):					# for lowerBoundOfSlice in 0 to 3
	upperBoundOfSlice = lowerBoundOfSlice + 1				
	while upperBoundOfSlice <= len(listOne):					# while upperBoundOfSlice is < or = 4
		subList = listOne[lowerBoundOfSlice:upperBoundOfSlice]	# obtaining a sublist using bounds
		subLists.append(subList)								# appending sublist to list containing sublists
		upperBoundOfSlice += 1									# incrementing upperBoundOfSlice

print(subLists)			# [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply