BatuDog88
BatuDog88

Reputation: 3

Iterate through ranges of elements in a list in Python

I am a beginner in Python and I have a doubt about iterating through a range of elements in a list.

I have this list:

['0.95', '0.05', '0.94', '0.06', '0.29', '0.71', '0.001', '0.999']

Suppose that, starting in the first position, I want to iterate through ranges of two elements: substituting the first two, leaving the next two as they were, and then substituting again the next two:

[-, -, '0.94', '0.06', -, -, '0.001', '0.999']

I also want to be able to start at any position. For example, using the same range as before, but starting in the third position:

['0.95', '0.05', -, -, '0.29', '0.71', -, -]

I have tried range with three parameters, but it only substitutes the first position in the range, not all the elements in the range.

Upvotes: 0

Views: 262

Answers (3)

Jens de Bruijn
Jens de Bruijn

Reputation: 969

Replace start with the required starting value.

l = ['0.95', '0.05', '0.94', '0.06', '0.29', '0.71', '0.001', '0.999']


def dash(l,start):
    for i in range(start,len(l)):
        if (i - start) % 4 == 0 or (i - start) % 4 == 1:
            l[i] = '-'
    return l

print dash(l,start = 2)

Upvotes: 0

t.pimentel
t.pimentel

Reputation: 1575

The simplest, and I think the best, way to do this is like this:

seq = [1,2,3,4,5,6,7,8]

replace_list= ['-','-','-','-']

seq[::4] = replace_list[::2]
seq[1::4] = replace_list[1::2]

print seq

Output:

['-', '-', 3, 4, '-', '-', 7, 8]

To start in which item to start just do:

replace_list= ['-','-','-']

starting_item=3
seq[starting_item::4] = replace_list[::2]
seq[starting_item+1::4] = replace_list[1::2]

Note that replace_list has to have the specific number of elements you want to substitute in seq list.

Output:

[1, 2, 3, '-', '-', 6, 7, '-']

If you want to replace all items always with same value, you can do:

starting_item=3

last_part = min((len(seq) - starting_item) % 4, 2)
size = ((len(seq) - starting_item)/4) * 2 + last_part
replace_list= ['-']*size

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

l = ['0.95', '0.05', '0.94', '0.06', '0.29', '0.71', '0.001', '0.999']

def subDashes(l, start):
    newL = []
    for index, elem in enumerate(l):
        if index%4 == start or index%4 == start+1:
            newL.append('-')
        else:
            newL.append(elem)
    return newL

>>> subDashes(l, 0)
['-', '-', '0.94', '0.06', '-', '-', '0.001', '0.999']

>>> subDashes(l, 1)
['0.95', '-', '-', '0.06', '0.29', '-', '-', '0.999']

>>> subDashes(l, 2)
['0.95', '0.05', '-', '-', '0.29', '0.71', '-', '-']

Upvotes: 2

Related Questions