![]() |
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 1: 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
Output :
The original list is : [5, 6, 8, 9, 10, 21, 3] Alternate Cyclic iteration is : [5, 3, 6, 21, 8, 10, 9] Time Complexity: O(n), where n is the length of the list test_list Method #2 : Using for loop This method uses two pointers i and j to traverse the original list from both ends simultaneously, and creates a new list result to store the alternate cyclic iteration of the original list. We iterate through the length of the original list using a loop for k in range(n), and use the modulus operator % to determine whether the current index k is even or odd. If it is even, we take the next element from the left end of the original list using lst[i] and store it in the result list at the current index k, and increment the left pointer i. If it is odd, we take the next element from the right end of the original list using lst[j] and store it in the result list at the current index k, and decrement the right pointer j. Finally, we print the original list and the alternate cyclic iteration list. Python3
Output
Original list: [5, 6, 8, 9, 10, 21, 3] Alternate cyclic iteration: [5, 3, 6, 21, 8, 10, 9] Time complexity: O(n) Method#3: Using the deque class and itertools module: Algorithm : 1. Create an empty list result to store the result of the iteration. Python3
Output
Original list: [5, 6, 8, 9, 10, 21, 3] Alternate cyclic iteration: [5, 3, 6, 21, 8, 10, 9] The time complexity: O(n), where n is the length of the input list. This is because the algorithm iterates over each element of the input list exactly once, and performs constant-time operations on each element. Method #4: using list slicing and concatenation. Step-by-step approach:
Python3
Output
Original list: [5, 6, 8, 9, 10, 21, 3] Alternate cyclic iteration: [5, 8, 10, 3, 21, 9, 6] Time complexity: O(n) |
Reffered: https://www.geeksforgeeks.org
Python |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |