Search code examples
pythonlistindices

Make a new list with a certain order, but skip some indices on if condition


I am trying to make an new list in a certain order that relies on another list. It should make an list with an order i specifed, but if an item in that other list is x it should skip that index and continue with the order without skipping an item in the order.

start:

days_list = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
x = 'rest'
order = ['a', 'b', 'c']

after i changed the days_list:

changed_days_list = ['sunday', 'monday', x, 'wednesday', x, 'friday', x]

The output should look like this:

example_output = ['a', 'b', 'rest', 'c', 'rest', 'a', 'rest']

I have tried with for and while loops, but i can't figure it out. Any thoughts?


Solution

  • You could use for-loop to check every value on changed_days_list and put new value from order when it is not rest. And you could use itertools.cycle() to get value from order.

    import itertools
    
    x = 'rest'
    
    order = ['a', 'b', 'c']
    changed_days_list = ['sunday', 'monday', x, 'wednesday', x, 'friday', x]
    
    cycle = itertools.cycle(order)
    
    result = []
    
    for item in changed_days_list:
        if item == x:
            result.append(item)
        else:
            next_value = next(cycle)
            result.append(next_value)
            
    print(result)
    

    Result:

    ['a', 'b', 'rest', 'c', 'rest', 'a', 'rest']