List and sublist python

How to get all sublists of a list in Python

In this post, we will learn how to print all sublists from a list in Python. The input of the program is a list and the output is a list holding all sublists. We will write one program that will take the list inputs one by one and print out the final output.

  • Take the total size of the list from the user.
  • Read the values one by one from the user.
  • Print out the final list of sublists.

Method 1: Get all sublists of a Python list with nested for loops:

We will use one nested for loop to find out all combinations of a list.

  • Run one loop in the range of 0 to length of the list.
  • Run one inner loop in the range of current outer loop to length of the list.
  • Get the slice of the list in between the current indices pointed by the outer loop and inner loop.
  • Add the sliced list to the final list.
  • Return the final list.

Below is the complete Python program:

= list() result_list = list() size = int(input('Enter the size of the list :')) print('Enter all elements of the list :') for i in range(size): given_list.append(int(input('Enter element to add : '))) for i in range(len(given_list) + 1): for j in range(i + 1, len(given_list) + 1): result_list.append(given_list[i:j]) print(given_list) print(result_list)
  • given_list is the original list entered by the user.
  • result_list is the final list i.e. lists of lists.
  • The size variable holds the size of the list. We are reading this value from the user.
  • The first for loop is used to read all values for the list one by one. We are using the input() method to read the values. Each value is converted to an integer with the int() method and appends to the list given_list .
  • The last nested for loops are used to create the final list. It uses list slicing to get the sublists.
  • At the end of the program, we are printing the original and the final lists.
Читайте также:  Выравнивание абзаца с помощью атрибута Style

This program will print the below output:

list :3 Enter all elements of the list : Enter element to add : 1 Enter element to add : 2 Enter element to add : 3 [1, 2, 3] [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]] Enter the size of the list :5 Enter all elements of the list : Enter element to add : 1 Enter element to add : 2 Enter element to add : 3 Enter element to add : 4 Enter element to add : 5 [1, 2, 3, 4, 5] [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2], [2, 3], [2, 3, 4], [2, 3, 4, 5], [3], [3, 4], [3, 4, 5], [4], [4, 5], [5]]

Method 2: Find the sublists of a list recursively:

This problem can also be solved recursively. With this approach, it will find the sublists of all the elements excluding the first element of the list recursively, append the elements with the first element and adds all to the final list.

def get_sublists(l): if len(l) == 0: return [[]] sublists = [] first = l[0] remaining = l[1:] sublist_remaining = get_sublists(remaining) for sublist in sublist_remaining: sublists.append([first] + sublist) sublists.extend(sublist_remaining) return sublists if __name__ == "__main__": given_list = list() result_list = list() size = int(input("Enter the size of the list: ")) print("Enter all elements of the list: ") for i in range(size): given_list.append(int(input("Enter element to add: "))) result_list = get_sublists(given_list) print(result_list)

Python get sublists from a list

list: 4 Enter all elements of the list: Enter element to add: 1 Enter element to add: 2 Enter element to add: 3 Enter element to add: 4 [[1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4], [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2], [3, 4], [3], [4], []]

Источник

Python: Slice Notation on List

The term slicing in programming usually refers to obtaining a substring, sub-tuple, or sublist from a string, tuple, or list respectively.

Python offers an array of straightforward ways to slice not only these three but any iterable. An iterable is, as the name suggests, any object that can be iterated over.

In this article, we’ll go over everything you need to know about Slicing Lists in Python.

Slicing a List in Python

There are a couple of ways to slice a list, most common of which is by using the : operator with the following syntax:

a_list[start:end] a_list[start:end:step] 

The start parameter represents the starting index, end is the ending index, and step is the number of items that are «stepped» over.

If step isn’t explicitly given, the default value is 1 . Note that the item with the index start will be included in the resulting sublist, but the item with the index end won’t be. The first element of a list has the index of 0 .

Example without the step parameter:

# A list of strings: a_list = ['May', 'the', 'Force', 'be', 'with', 'you.'] sublist = a_list[1:3] print(sublist) 

To skip every other word, set step to 2 :

a_list = ['The', 'Force', 'will', 'be', 'with', 'you.', 'Always.'] sublist = a_list[1:8:2] print(sublist) 

If step isn’t listed, the sublist will start from the beginning. Likewise, if end isn’t listed, the sublist will end at the ending of the original list:

a_list = ['Do.', 'Or', 'do', 'not.', 'There', 'is', 'no', 'try.'] sublist = a_list[:4] print(sublist) sublist = a_list[4:] print(sublist) 

That snippet of code prints out:

['Do.', 'Or', 'do', 'not.'] ['There', 'is', 'no', 'try.'] 

Finding the Head and Tail of List with Slice Notation

The slice notation can be used with negative indexing as well. Negative indexing works the same way as regular indexing, except for the fact that it starts indexing from the last element which has the index -1 .

This can be used to obtain the head and tail of a list of a given length. The head of a list is a sublist that contains the first n elements of a list, and the tail is a sublist that contains the last n elements.

Let’s go ahead and separate a tail and head of a list:

# The length of the tail n = 2 a_list = ['Never', 'tell', 'me', 'the', 'odds!'] # Head of the list: sublist = a_list[:n] print(sublist) # Tail of the list: sublist = a_list[-n:] print(sublist) 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Using Slice Notation to Reverse a List

Even the step parameter can be negative. If we set it to a negative value, the resulting list will be reversed, with the step value. Instead of stepping forward, we’re stepping backwards, from the end of the list to the start and including these elements:

a_list = ['Power!', 'Unlimited', 'power!'] sublist = a_list[::-1] print(sublist) 

Replacing Elements of a Sublist with Slice Notation

The slice notation can be used to asign new values to elements of a certain sublist. For example, let try to replace the tail and the head of a list:

a_list = ['I', 'am', 'no', 'Jedi.'] print(a_list) # Replacing the head of a list a_list[:1] = ['You', 'are'] print(a_list) # Replacing the tail of a list a_list[-1:] = ['Sith'] print(a_list) 
['I', 'am', 'no', 'Jedi.'] ['You', 'are', 'no', 'Jedi.'] ['You', 'are', 'no', 'Sith'] 

Replacing Every n-th Element of a List with Slice Notation

An easy way to replace every n-th element of a list is to set the step parameter to n in the slicing notation:

 a_list = ['I’m', 'just', 'a', 'simple', 'man', 'trying', 'to', 'make', 'my', 'way', 'in', 'the', 'universe.'] print(a_list) # Replacing every other word starting with the word with the index 1 a_list[1::2] = ['only', 'common', 'attempting','do', 'best','the'] print(a_list) 
['I’m', 'just', 'a', 'simple', 'man', 'trying', 'to', 'make', 'my', 'way', 'in', 'the', 'universe.'] ['just', 'simple', 'trying', 'make', 'way', 'the'] ['I’m', 'only', 'a', 'common', 'man', 'attempting', 'to', 'do', 'my', 'best', 'in', 'the', 'universe.'] 

Conclusion

Slicing any sequence in Python is easy, simple, and intuitive. Negative indexing offers an easy way to acquire the first or last few elements of a sequence, or reverse its order.

In this article, we’ve covered how to apply the Slice Notation on Lists in Python.

Источник

How to get sub list by slicing a Python List

Slicing means accessing a range of list. We can do slicing by providing two indices separated by a colon.

The first value is the start index and the second value is the to index. The start index is inclusive and to index is exclusive.

 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print numbers[3:6] print numbers[0:1] 

The code above generates the following result.

Just as indexing we can do slicing from the right of a list.

To slice from the end of a list we can omit the second index and use negative value for the first index.

 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print numbers[-3:-1] 

The code above generates the following result.

If the leftmost index in a slice comes later in the sequence than the second one, the result is an empty sequence.

We can use a shortcut: If the slice continues to the end of the sequence, you may simply leave out the last index:

 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print numbers[-3:] 

The same thing works from the beginning:

 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] numbers[:3] 

To copy the entire sequence, you may leave out both indices:

 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print numbers[:] 

Slicing is very useful for extracting parts of a list. The following code splits up a URL of the form http://www.something.com.

 url = 'http://www.java2s.com.com' domain = url[11:-4] print "Domain name: " + domain 

The code above generates the following result.

Источник

Оцените статью