Python | Print list elements in circular range
Given a list of elements, the task is to print element in group of k till n-iteration in circular range.
Examples:
Input: list = [1, 2, 3, 4, 5, 6, 7], k = 3, n =10 Output: [1, 2, 3] [4, 5, 6] [7, 1, 2] [3, 4, 5] [6, 7, 1] [2, 3, 4] [5, 6, 7] [1, 2, 3] [4, 5, 6] [7, 1, 2] Input: list = [10, 20, 30, 40, 50, 60, 70], k = 4, n = 5 Output: [10, 20, 30, 40] [50, 60, 70, 10] [20, 30, 40, 50] [60, 70, 10, 20] [30, 40, 50, 60]
We can use itertools with zip to do this task.
Example #1:
# Python code to print element in group # of 5 till 9 iteration in circular range. # Importing from itertools import cycle # list initialization List = [90, 99, 192, 0, 43, 55] # Defining no of iterations n = 9 # Defining no of grouping k = 5 for index, *ans in zip(range(n), *[cycle(List)] * k): # printing ans print(ans) |
chevron_right
filter_none
Output:
[90, 99, 192, 0, 43] [55, 90, 99, 192, 0] [43, 55, 90, 99, 192] [0, 43, 55, 90, 99] [192, 0, 43, 55, 90] [99, 192, 0, 43, 55] [90, 99, 192, 0, 43] [55, 90, 99, 192, 0] [43, 55, 90, 99, 192]
Example #2:
# Python code to print element in group # of 6 till 4 iteration in circular range. # Importing from itertools import cycle # list initialization List = ['Geeks', 'for', 'geeks', 'is', 'portal'] # Defining no of iterations n = 4 # Defining no of grouping k = 6 for index, *ans in zip(range(n), *[cycle(List)] * k): # printing ans print(ans) |
chevron_right
filter_none
Output:
['Geeks', 'for', 'geeks', 'is', 'portal', 'Geeks'] ['for', 'geeks', 'is', 'portal', 'Geeks', 'for'] ['geeks', 'is', 'portal', 'Geeks', 'for', 'geeks'] ['is', 'portal', 'Geeks', 'for', 'geeks', 'is']
Recommended Posts:
- range() to a list in Python
- Python | Maximum sum of elements of list in a list of lists
- Python | Numbers in a list within a given range
- Python program to print all odd numbers in a range
- Python program to print all even numbers in a range
- Python List Comprehension | Three way partitioning of an array around a given range
- Python program to print all positive numbers in a range
- Python program to print all negative numbers in a range
- Program to print N minimum elements from list of integers
- Python | Generate random numbers within a given range and store in a list
- Python Program for Number of elements with odd factors in given range
- Python | Print all sublists of a list
- Python | Get first and last elements of a list
- Python | Remove and print every third from list until it becomes empty
- Python program to print odd numbers in a List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



