Thursday, November 21, 2024
Google search engine
HomeLanguagesPython | Custom Cycle list

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 elements from which cycling starts and Number of elements in cycle list. Let’s discuss solution to these variation. 

Method : Using dropwhile() + cycle() + islice() This task can be performed using combination of above functions. In this, the elements are dropped till K with dropwhile(), then the cycle can be done using cycle() and islice() is used to restrict the count of elements in list. 

Python3




# Python3 code to demonstrate working of
# Custom Cycle list
# using dropwhile() + cycle() + islice()
import itertools
 
# initialize list
test_list = [3, 4, 5, 7, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize element for start cycle
K = 7
 
# initialize size of cycle list
N = 12
 
# Custom Cycle list
# using dropwhile() + cycle() + islice()
res = list(itertools.islice(itertools.dropwhile(lambda i: i != K, itertools.cycle(test_list)),  N))
 
# printing result
print("The cycled list is : " + str(res))


Output : 

The original list is : [3, 4, 5, 7, 1]
The cycled list is : [7, 1, 3, 4, 5, 7, 1, 3, 4, 5, 7, 1]

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 

Using list comprehension:

Approach:

We can use list comprehension to create a new list containing the elements of the original list repeated a certain number of times.

Python3




lst = [1, 2, 3]
m = 4
new_lst = [x for i in range(m) for x in lst]
print(new_lst)


Output

[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

Time complexity: O(nm)
Auxiliary Space: O(nm)

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments