'int' object does not support item assignment - python

This is my code,and it appears a problem like the topic. i am a primary learner and i don't know where is the problem. could u help me fix the code and tell me which part of knowledge i need to review. thanks in advance.
x = int(raw_input("enter the value of x:"))
y = int(raw_input("enter the value of y:"))
i = 0
j = 0
array=[x*y]
for i in range(x):
array.append([0 for j in range(y)])
for i in range(x-1):
for j in range(y-1):
array[i][j]=i * j
print array

The problem is that you are creating a list of mixed types, integers and lists, and then trying to access the integer value as if it was a list.
Let's use a simple example:
x = 2
y = 3
i = 0
j = 0
array = [x*y]
Now, let's look at what array currently contains:
array
>> 6
Now we run your first for loop:
for i in range(x):
array.append([0 for j in range(y)])
And let's check the new value of array:
array
>> [6, [0, 0, 0], [0, 0, 0]]
So now we see that the first element of array is an integer. The remaining elements are all lists with three elements.
The error occurs in the first pass through your nested for loops. In the first pass, i and j are both zero.
array[0][0] = 0*0
>> TypeError: 'int' object does not support item assignment
Since array[0] is an integer, you can't use the second [0]. There is nothing there to get. So, like Ashalynd said, the array = x*y seems to be the problem.
Depending on what you really want to do, there could be many solutions. Let's assume you want the first element of your list to be a list of length y, with each value equal to x*y. Then replace array = [x*y] with:
array = [x*y for i in range(y)]

Try inspect your array.
array[2*3] will result in [6].
array.append([0 for j in range(3)]) will then result in [6,[0,0,0]], your first element is not an array.
There is in indent error with your for loops.
I think what you are trying to do is this:
array2=[]
for i in range(2):
array2.append([0 for j in range(3)])

Your syntax is so wrong. First of all if you store variables i=0, j=0 so why you use them in for loop? It doesn't make any sense.
Second, just debug it, put print (array) after the list.
if x=5 and y=5 ;
[25, [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0,
0], [0, 0, 0, 0, 0]]
This is your array, and this line;
array[i][j]=i * j
Throwing error? Why? Because;
j=0
i=0
array[i]=25
array[i][j] = 2
So that's why you got error.Integers, which is 2 here, doesn't support item assignment. Try to fix your syntax.

Related

How to add a 1 into a list based on the values of another list, which give the position of where 1 should go

I have two lists:
a = [1,4,5]
x = [0,0,0,0,0,0,0,0,0,0]
I am stuck on making it so that it could look like this:
x= [0,1,0,0,1,1,0,0,0,0,0]
So that the number 1 is added to list x based on the value of list a, where the list values in a determine the position of where 1 should go. I am not sure if that makes much sense but it would help a lot.
You can use a for loop to iterate through list a and set the indexes of list x of its values to 1. So for example:
a = [1, 4, 5]
x = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for index in a: # Iterating through the list a
x[index] = 1 # Setting the values to 1
print(x)
Alternative way,
using numpy fast and efficient
np_x = np.array(x)
np_x[a]=1

how do I change assign values to array I pass to a function?

I have a 5x2 dimensional array which I want to assign specific values to, but I'm having trouble doing so even looking at multiple explanations of Python passing by value rather than reference. The relevant code is as follows:
def do_something(x, y):
x = 0
y = 0
return_value = -1 #error may occur in this code
#some complex operation is performed that manipulates x and y
return_value = 0
return return_value
def main():
result = [[0]*5]*2
for i in range(5):
do_something(result[i][0], result[i][1])
I clearly can't say result = do_something(...) because I still want to know what do_something returned to see if the complex operation is done right. Append doesn't exactly solve my problem, because x and y are manipulated inside the code. Result[i].append(...) would work if I knew what I wanted to append. But even when the complex operation goes right, the array doesn't change.
(I have tried passing result, then r.append(...) but that doesn't work either) Any help?
There is no problem in do_something function.
At main function,
result = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
So, please change as below code.
do_something(result[0][i], result[0][i])
Python does pass parameters by reference. However, there are two points to consider:
First, when passing immutable types like integers, floats, strings etc. they will not be effected by the code running in the function.
x = 1.0
def int_do_somthing(x):
x += 1
int_do_somthing(x)
print(x) # 1.0
Second, when you reassign the value of a variable to a new variable within the function scope, the original one is not effected.
l = [1,1,1]
def do_nothing(l):
l = l + [2] # defines a new l that only exist in the function scope
do_nothing(l)
print(l) # [1,1,1]
def do_somthing(l):
l += [2] # modify existing l
do_somthing(l)
print(l) # [1,1,1,2]
So in your case, pass array slices, not individual values to the function, and dont reassign the entire slice but rather edit the values they contain (access with [] operator).
result[i][0] and result[i][1] are integer type values. Since integer is primitive type, changing their values inside the function won't affect the actual values outside the list. You should pass in the list instead since it is not a primitive type and thus any changes you made inside the function will also affect the list outside the function.
Also, you probably don't want to use result = [[0]*5]*2 to initialize your array. One reason is that it will initialize a 2x5 array instead of 5x2. The other more important reason is that it will only duplicate the reference to the list [0, 0, 0, 0, 0] twice. Therefore, if you change only 1 value inside a row, the other row will also have that value. For example:
result = [[0] * 5] * 2
print(result) # This will print out [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
result[0][1] = 1
print(result) # This will print out [[0, 1, 0, 0, 0], [0, 1, 0, 0, 0]]
The alternative way you can do is to use result = [[0 for x in range(5)] for y in range(2)] which will give array with desired values but they are not duplicated reference like the above.
result = [[0 for x in range(5)] for y in range(2)]
print(result) # This will print out [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
result[0][1] = 1
print(result) # This will print out [[0, 1, 0, 0, 0], [0, 0, 0, 0, 0]]
I've modified your code according to my suggestion and it seems to work well:
def do_something(arr):
# Assign value below
arr[0] = 1
arr[1] = 2
def main():
result = [[0 for x in range(2)] for y in range(5)]
for i in range(5):
do_something(result[i])
print result
main()

Assigning a random number to individual array elements that meet a certain criteria

I need to find all the elements in an array that are >0 and then replace each one with a random number between 0 and 5 in Python 3.
I have made an array (called L) of 20 elements that each equal 0 or 1, but am struggling to replace elements individually. (However in future this may equal a range of numbers, so I need >0 and not just =1)
I do not want
speed = np.random.randint(0,5)
L[L > 0] = speed
as this changed all the elements >0 to the same random number.
Any ideas?
Perhaps this will help you.
from random import *
L = [0,0,1,0,1,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0]
i=0
for n in L:
x = randint(1, 5) # Pick a random number between 1 and 5.
if n > 0:
L[i] = x
i+=1
print(L)
Perhaps this?
I instantiate L with a special pattern, so that it should be easy to discern if the code does what's intended.
>>> import random
>>> L = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
>>> list(map(lambda x: random.randint(0,5) if x>0 else x, L))
[0, 0, 0, 0, 0, 3, 2, 2, 4, 5]
I should mention that this code does not replace individual elements in L. It creates a new list. However, unless the list is especially large this would make no difference, in fact might be slightly faster. (This might be why someone down-voted. You just can't please everyone.)

IndexError: list index out of range when try to start range from 1

I have the following working code.
b=4
c=4
mylist = []
for s in range(b):
mylist.append([])
for g in range(c):
mylist[s].append(0)
print mylist
which gives the following output.
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
However for my requirement I want to start the range from the first element. Hence I wrote the code as follows:
b=4
c=4
mylist = []
for s in range(1,b):
mylist.append([])
for g in range(1,c):
mylist[s].append(0)
print mylist
But this is giving me the error
IndexError: list index out of range
I don't understand why. Please clarify if you know why.
Thanks.
Lists are zero based, the first append always creates l[0]. You need to fix your indices;
b=4
c=4
mylist = []
for s in range(1,b):
mylist.append([])
for g in range(1,c):
mylist[s-1].append(0) # have to subtract 1 to get back to zero-based index
print mylist
your output then looks like this;
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for s in range(1,b):
mylist.append([])
for g in range(1,c):
mylist[s].append(0)
In this loop, you're appending an empty list to mylist. mylist thusly only has one element in it, but within the second loop, you're trying to access mylist[1] when s == 1. This is why you're getting an Index Error.
Hope this helps!
As we know python list start from 0.
You can add a dummy object at index 0 to start from 1 then pop it at the end
Your code must be like this
b=4
c=4
mylist = ['dummy']
for s in range(1,b):
mylist.append([])
for g in range(1,c):
mylist[s].append(0)
mylist.pop(0)
print mylist

Declaring and populating 2D array in python

I want to declare and populate a 2d array in python as follow:
def randomNo():
rn = randint(0, 4)
return rn
def populateStatus():
status = []
status.append([])
for x in range (0,4):
for y in range (0,4):
status[x].append(randomNo())
But I always get IndexError: list index out of range exception. Any ideas?
More "modern python" way of doing things.
[[ randint(0,4) for x in range(0,4)] for y in range(0,4)]
Its simply a pair of nested list comprehensions.
The only time when you add 'rows' to the status array is before the outer for loop.
So - status[0] exists but status[1] does not.
you need to move status.append([]) to be inside the outer for loop and then it will create a new 'row' before you try to populate it.
You haven't increase the number of rows in status for every value of x
for x in range(0,4):
status.append([])
for y in range(0,4):
status[x].append(randomNo())
If you're question is about generating an array of random integers, the numpy module can be useful:
import numpy as np
np.random.randint(0,4, size=(4,4))
This yields directly
array([[3, 0, 1, 1],
[0, 1, 1, 2],
[2, 0, 3, 2],
[0, 1, 2, 2]])

Categories