Python | Alternate Cycling in list
Last Updated :
09 May, 2023
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
from itertools import islice, cycle
test_list = [ 5 , 6 , 8 , 9 , 10 , 21 , 3 ]
print ("The original list is : " + str (test_list))
res = [ next (i) for i in islice(cycle(( iter (test_list),
reversed (test_list))), len (test_list))]
print ("Alternate Cyclic iteration is : " + str (res))
|
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
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res 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
lst = [ 5 , 6 , 8 , 9 , 10 , 21 , 3 ]
n = len (lst)
result = [ 0 ] * n
i = 0
j = n - 1
for k in range (n):
if k % 2 = = 0 :
result[k] = lst[i]
i + = 1
else :
result[k] = lst[j]
j - = 1
print ( "Original list:" , lst)
print ( "Alternate cyclic iteration:" , result)
|
Output
Original list: [5, 6, 8, 9, 10, 21, 3]
Alternate cyclic iteration: [5, 3, 6, 21, 8, 10, 9]
Time complexity: O(n)
Auxiliary Space: 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.
2. Create two variables i and j, initialized to 0 and len(lst) – 1, respectively.
3. Iterate over the indices k of the input list lst, from 0 to len(lst) – 1.
4.If k is even, append lst[i] to the result list, and increment i.
5.If k is odd, append lst[j] to the result list, and decrement j.
6. When the iteration is complete, return the result list.
Python3
from collections import deque
lst = [ 5 , 6 , 8 , 9 , 10 , 21 , 3 ]
d = deque(lst)
result = []
while d:
result.append(d.popleft())
if d:
result.append(d.pop())
print ( "Original list:" , lst)
print ( "Alternate cyclic iteration:" , result)
|
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.
The space complexity: O(n), because the deque d and the result list result both have a maximum size of n. Therefore, the algorithm uses O(n) additional memory beyond the input list.
Method #4: using list slicing and concatenation.
Step-by-step approach:
- Initialize an empty list result to store the alternate cyclic iteration of the given list.
- Create two sublists even and odd using list slicing. The even sublist contains elements with even indices (i.e., 0, 2, 4, …) and the odd sublist contains elements with odd indices (i.e., 1, 3, 5, …).
- Reverse the odd sublist using the [::-1] slice notation.
- Concatenate the even and odd sublists using the + operator.
- Assign the concatenated list to result.
- Print the original list and the alternate cyclic iteration list.
Python3
lst = [ 5 , 6 , 8 , 9 , 10 , 21 , 3 ]
n = len (lst)
result = []
even = lst[:: 2 ]
odd = lst[ 1 :: 2 ][:: - 1 ]
result = even + odd
print ( "Original list:" , lst)
print ( "Alternate cyclic iteration:" , result)
|
Output
Original list: [5, 6, 8, 9, 10, 21, 3]
Alternate cyclic iteration: [5, 8, 10, 3, 21, 9, 6]
Time complexity: O(n)
Auxiliary space: O(n) for the result list.
Similar Reads
Extending a list in Python
In Python, a list is one of the most widely used data structures for storing multiple items in a single variable. Often, we need to extend a list by adding one or more elements, either from another list or other iterable objects. Python provides several ways to achieve this. In this article, we will
2 min read
Cloning or Copying a List - Python
In Python, lists are mutable, meaning they can be modified after creation. Often, we may need to create a copy of a list to preserve the original data while making changes to the duplicate. Cloning or copying a list can be done in multiple ways, each with its own characteristics. Let's discuss vario
3 min read
Python | Add element at alternate position in list
Sometimes, while working with Python list, we can have a problem in which we need to add elements in list alternatively i.e at even positions and reorder the list accordingly. This has a potential application in many domains such as day-day programming and competitive programming. Let's discuss cert
2 min read
Circular Linked List in Python
A Circular Linked List is a variation of the standard linked list. In a standard linked list, the last element points to null, indicating the end of the list. However, in a circular linked list, the last element points back to the first element, forming a loop. In this article, we will discuss the c
13 min read
Python | Custom Cycle list
While working with Python lists, we can have a problem in which we need to perform the cycle of lists. This problem looks quite straight forward and has been discussed earlier. But sometimes, we need to perform it's variations, hence making task challenging. We can have customizations such as elemen
2 min read
Access List Items in Python
Accessing elements of a list is a common operation and can be done using different techniques. Below, we explore these methods in order of efficiency and their use cases. Indexing is the simplest and most direct way to access specific items in a list. Every item in a list has an index starting from
2 min read
Pass a List to a Function in Python
In Python, we can pass a list to a function, allowing to access or update the list's items. This makes the function more versatile and allows us to work with the list in many ways. Passing list by Reference When we pass a list to a function by reference, it refers to the original list. If we make an
2 min read
Flipping the boolean values in a Python list
Flipping boolean values in a list involves changing True to False and False to True. This operation is straightforward in Python and can be accomplished using various methods. In this article, we'll explore different techniques to flip boolean values in a list in Python. 1. Using List ComprehensionL
3 min read
Python - Change List Item
Lists in Python are mutable meaning their items can be changed after the list is created. Modifying elements in a list is a common task, whether we're replacing an item at a specific index, updating multiple items at once, or using conditions to modify certain elements. This article explores the dif
3 min read
Iterate over a list in Python
Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly. Example: Print all elements in the list one by one using for loop. [GFGTABS] Python a = [1, 3, 5, 7,
3 min read