Python | Alternate Cycling in list
Sometimes, while working with a Python list, we can have a problem in which we need to perform the access/printing of list in different ways. In some variations, there might be a need for printing the list in an alternate cyclic way, i.e printing elements from front and read alternatively. This is a popular problem in-school programming. Let’s discuss a certain way in which this task can be performed.
Method : Using reversed() + islice() + iter() + cycle() + next() + list comprehension
The combination of above functions can be employed to perform this task. In this, reversed() and iter() are used to create iterators of reversed and normal sequence list respectively, cycle() performs the task of alternate access. The islice() performs the task of extracting the elements and construct to new list. The next() performs the task of accessing elements.
Code :
# Python3 code to demonstrate working of # Alternate Cycling in list # using reversed() + islice() + iter() + cycle() + next() + list comprehension from itertools import islice, cycle # initialize list test_list = [5, 6, 8, 9, 10, 21, 3] # printing original list print("The original list is : " + str(test_list)) # Alternate Cycling in list # using reversed() + islice() + iter() + cycle() + next() + list comprehension res = [next(i) for i in islice(cycle((iter(test_list), reversed(test_list))), len(test_list))] # printing result print("Alternate Cyclic iteration is : " + str(res)) |
The original list is : [5, 6, 8, 9, 10, 21, 3] Alternate Cyclic iteration is : [5, 3, 6, 21, 8, 10, 9]
Recommended Posts:
- Python | List Initialization with alternate 0s and 1s
- Python | Add element at alternate position in list
- Python | Alternate element summation in list
- Python | Alternate range slicing in list
- Python | List consisting of all the alternate elements
- Python | Increasing alternate element pattern in list
- Python | Convert list of tuples to list of list
- Python | Convert list of string to list of list
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Convert list of string into sorted list of integer
- Python | Find maximum length sub-list in a nested list
- Python | Pair and combine nested list to tuple list
- Python | Convert list of numerical string to list of Integers
- Python | Replace elements in second list with index of same element in first list
- Python | Merge List with common elements in a List of Lists
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.



