- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Split List on next larger value
When it is required to split a list based on the next larger value, a list comprehension, the ‘iter’ method and the ‘islice’ methods are used.
Below is a demonstration of the same −
from itertools import islice my_list = [11, 22, 33, 34, 45, 26, 87,11] print("The list is :") print(my_list) length_to_split = [2, 5, 3] print("The split length list is :") print(length_to_split) temp = iter(my_list) my_result = [list(islice(temp, element)) for element in length_to_split] print("The result is :") print(my_result)
The list is : [11, 22, 33, 34, 45, 26, 87, 11] The split length list is : [2, 5, 3] The result is : [[11, 22], [33, 34, 45, 26, 87], ]
The required packages are imported into the environment.
A list of integers is defined and is displayed on the console.
Another list of integers is defined and is displayed on the console.
The ‘iter’ method is called on the list, and assigned to a variable.
A list comprehension is used to iterate over the elements, and the ‘islice’ method is used.
This is converted to a list and is assigned to a variable.
This is the output that is displayed on the console.
- Next Larger element in n-ary tree in C++
- Custom list split in Python
- Program to merge two sorted list to form larger sorted list in Python
- Python – Next N elements from K value
- Python – Split Strings on Prefix Occurrence
- Split List in C++
- Python - Split list into all possible tuple pairs
- How to split string on whitespace in Python?
- How to split strings on multiple delimiters with Python?
- Water on Mars. Is Life next?
- Next Permutation in Python
- Program to arrange linked list nodes based on the value k in Python
- Python - Clearing list as dictionary value
- Point to next higher value node in a linked list with an arbitrary pointer in C++