user9050906
user9050906

Reputation:

Python. Replace elements using slice

I need to implement Sieve of Eratosthenes algorithm. I have list:
bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
I need to replace each odd element with "0". Now I have code:

while viewIndex < maxNumber:
    bar[viewIndex] = 0
    viewIndex += 2

But I remember about slices. And for me it will be nice to write something like this:

bar[currentIndex::2] = 0

But I have error:

TypeError: must assign iterable to extended slice

Maybe you know a beautiful solution to this task.

Upvotes: 3

Views: 4955

Answers (5)

eric
eric

Reputation: 8019

I use numpy:

foo = np.ones(10)
foo[1::2] = 2

This just works.

You shouldn't have to keep track of indices -- the point of slicing is to make things more convenient, not to force you to keep track of which day of the week relative to the third Tuesday of last month you bought bread.

Upvotes: 1

user9050906
user9050906

Reputation:

Thank to all for answers. My implementation of Sieve of Eatosthenes algorithm:

def resheto(data): 
     print("\tStart Resheto") 
     currentIndex = 0 

     while currentIndex < len(data) - 1: 
         data[currentIndex + data[currentIndex]::data[currentIndex]] = \
             [0] * ((len(data) + 1) // data[currentIndex] - 1) 
         currentIndex += 1 

         while currentIndex < len(data) - 1 and data[currentIndex] == 0: 
             currentIndex += 1 

         if currentIndex >= len(data) - 1: 
             break 
print("\tEnd Resheto") return data

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78546

You should assign the slice to an iterable of the same length as the number of odds:

bar[1::2] = [0]*(len(bar)//2)
print(bar)
# [2, 0, 4, 0, 6, 0, 8, 0, 10]

To extend this for even indices, you need to take into consideration lists with odd-lengths (not relevant for the above case) by adding the modulo 2 value of the list length:

bar[::2] = [0]*(len(bar)//2 + len(bar)%2)

Which is same as:

bar[::2] = [0]*sum(divmod(len(bar), 2))

Upvotes: 5

Manjunath
Manjunath

Reputation: 150

You can use map to set elements on odd index to zero,

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
print map(lambda i: 0 if bar.index(i)%2!=0 else i, bar)

[2, 0, 4, 0, 6, 0, 8, 0, 10]

or if you want to set odd element value to zero, you can do this,

map(lambda i: 0 if i%2!=0 else i, bar)

Upvotes: 0

sachin dubey
sachin dubey

Reputation: 779

Use simple for loop

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in  range(len(bar)):
   if bar[i] % 2 != 0:
       bar[i] = 0
print(bar)

Output

[2, 0, 4, 0, 6, 0, 8, 0, 10]

Upvotes: 0

Related Questions