1

I've an array, for example:

Array = [100]*100

Then I want to do this:

Array[0:10] = 1

The Array should look like this:

Array = [1,1,1,1,1,1,1,1,1,1,100,100....,100]

But Python says No and gives me

Array[0:10] = 1 can only assign an iterable

What does it want and how can I fix it?

1
  • 7
    Array[0:10] = [1]*10 Commented Aug 14, 2018 at 9:54

5 Answers 5

10

You can use array[0:10] = [1] * 10, you just need to make an array of the size of the slice you are replacing.

Sign up to request clarification or add additional context in comments.

Comments

5

Another way is to turn your list into a numpy array, and numpy will broadcast your value to the whole part of the array:

import numpy as np

a = np.array([100]*100)

a[0:10] = 1
print(a)

# array([  1,   1,   1,   1,   1,   1,   1,   1,   1,   1, 100, 100, 100,
#        100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
#        ... 
#       ])

1 Comment

Very clever. Thank you.
1

I'll give you an example with list:

L = [0 for k in range(100)] # List of 0
L[10:20] = [1 for k in range(10)]

# Output:
L = [0, ..., 0, 1, 1, ..., 1, 0, ..., 0]

You need to give a list as well to replace N values.

11 Comments

Thank you. I prefer jc1850 solution better but I'll keep that in mind.
@Quotenbanane That's exactly the same, I just defined the replacing list on the right side differently. You should also have a look at the solution given by Thierry Lathuile, which involves numpy. Try to read about the difference between a list and a numpy array.
well you made a little extra work with [1 for k in range(10)] didn't you?
Yeah, Thierry's answer is awesome, i agree. But i do not need numpy right now.
@Quotenbanane That's just creating a list of 1 of size 10. Exactly the same as [1] * 10. However, indeed, it's not as efficient.
|
1

the type of operands in both side should be same in this case

Array[0:10]=[1]*10

Comments

1

lists in python are mutable it's not good to write them in the form [100]*100. You might have problems later when your code gets complicated.

I suggest to write it as:

array = [100 for _ in range(100)]
for i in range(10):
    array[i] = 1
print(array)

output: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.