Having adding to dictionary problems python - python

This is part of my code:
add_values=[2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for each in add_values:
print(each)
s=add_values[each]
s=int(s)
h=s*100
mydict[add_values[each]]=s
And it is bringing up this error:
IndexError: list index out of range
(For the s=add_values[each] line)
Please can you tell what is wrong here and what needs changing,
Thanks.

Think about reaching the fifth item in add_values:
for each in add_values:
print(each) # each == 50
s=add_values[each] # what's the fiftieth item in 'add_values'?!
You don't need to index into add_values, you are already accessing the value - replace add_values[each] with, simply, each.

each is the value, you can't use it as an index (mainly because the size of add_values is 14 and you have values that are greater than this inside add_values):
add_values=[2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for each in add_values:
print(each)
s=each
s=int(s)
h=s*100
mydict[each]=s
Another solution would be to use an index:
add_values=[2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for i in range(len(add_values)):
print(add_values[i])
s=add_values[i]
s=int(s)
h=s*100
mydict[add_values[i]]=s

You are using an array element as an array index, which is why you are getting an out-of-bounds error.
With Python's for loop notation, you don't need to access an index explicitly; just access the element, which in your case is each:
for each in add_values:
print(each)
s=each # kind of redundant, but this should work

for each in add_value sets each to 2, 5, 10, 20, 50, etc. On the 4th iteration of the loop, each is 20. When you say add_values[each], you get an error because add_values has only 14 elements and you're trying to access element number 20. You'd get in even more trouble if it tried to access element number 50000.

Related

python logic setting variable to none

Ive done enough research to understand my logic (I believe):
I have python code to set a variable to None so that at the db level it stores the value of this variable to Null.
Logic looks like:
# when properly set to something other than `None` an example value might be: ['6.1 ', 'Medium'
thesev=cve.find("span", class_="label-warning").text
thesevcat=re.split("- ", str(thesev))
if thesevcat is None:
thesevcat=None
else:
#looking to set thesevcat='Medium' for example
thesevcat=thesevcat[1]
sometimes thesevcat is successfully parsed the value, othertimes it cant parse it, so I want to set it to None
However, I keep getting this error:
thesevcat=thesevcat[1]
IndexError: list index out of range
what is going wrong here? Thanks
thesevcat=thesevcat[1]
IndexError: list index out of range
List index out of range is pretty explicit, it means that if thesevcat is in fact a list (which we don't really know seeing your code but I guess it is), it doesn't have a 2nd index, which means it's a list containing in maximum one element (for instance ["medium"] )
Please keep in mind that the first index of a list is 0, so if your list is your_list = ["medium"], to access "medium", you need to write your_list[0]
if you wanted to access the 2nd element of your list, then your list would need to be at least 2 element long, then you'd access it with the index 1
for instance:
your_list = ["medium", "large"]
print(your_list[1])
# would print large

python slicing [:-N] [:-N+1]

I been trying to code the following line but I get the message that operands could not be broadcast together with shapes (0,) (30,)
x has a length of 32
x[:-N+1] I want to access all elements except the last two
x[N:-N] I want to access all elements except the first one and the last one
x[N+1:] I want to access all elements except the first
y = x[:-N+1] - 2 * x[N:-N] + x[N+1:]
How should I index x to access those values? I'm new to python so any tips would be appreciated.
Slice except the last two: x[:N-2]
Except first and last: x[1:N-1]
Except first two: x[2:]
Python slice can be obtained by:
x[starting_index:end_index] {including starting_index element and excluding end_index}
If you don't specify the starting_index, it becomes 0 by default.
If you don't specify the end_index, it becomes N by default.
Considering the list length might be vary, the python has good apporach to access the items of a list.
Given a alist=['a','b','something',1,2]
if you use alist[1:], you will get ['b', 'something', 1, 2]
if you use alist[:1], you will get ['a','b','something',1]
if you only use alist[1], you will only get a ,which is the first item of the list.
so, if you use alist[-1:], you will get 2 , which is the first item starts from right.
if you use alist[:-1], you will get ['a','b','something',1] , which are items start from right except the fist.
In conclusion, the empty thing in the [:] is what you will get after use slicing.

Find max values in a nested list in Python

I want to find the index of max values in a nested list:
For example the nested list is:
[[15 16 18 19 12 11] [13 19 23 21 16 12] [12 15 17 19 20 10] [10 14 16 13 9 6]]
the max values should be 19, 23, 20, 16.
I also want to find their index in tuple format such as
19: (0,3) 23:(1,2) 20: (2,4)
I know how to find the global maximum of the nested list, but not sure how to find the max values for each list.
You just need a for loop to solve this.
I'll give you a real answer, but you will want to look into this more to understand what is going on:
for ii,line in enumerate(data):
max_val = max(line)
index = line.index(max_val)
print("{}:({},{})".format(max_val,ii,index),end=' ')
print()
a for loop in python is going to give you each element in an iterable. In this case you've got a list-of-lists, so each line is going to be a list. Since you want those numbered, I've put the data inside the enumerate function, which returns a pair of (,<element) which the for loop unpacks into the variables ii and line.
The next line max_val is assigned by the max function which returns the maximum value in the iterable line.
The index variable is set by the method list.index of the line list instance, which returns the first index of the value given to it in the list the method is called on.
Finally I print the output in the format you want by using a string and calling the format method to fill in the {} placeholders. more information on format strings can be found here. Also, the print function defaults to a newline after each print; so rather than introduce string-building here, I changed the end-line to a space and added an extra print after the for-loop to get you a new-line.
There's a lot here, and I can see how you might be lost on this question. I'm going to link to each of the built-in commands I used here so that you can learn more about python's "batteries included" functions and methods.
for-loop flow control
Built-in functions:
enumerate
max
print
Python built-in data structures
lists
Happy hacking.
to solve your problem, i'd probably go with a dictionary comprehension (which is actually working the same way as list comprehensions)
{max(nested_list): (i, nested_list.index(max(nested_list))) for i, nested_list in enumerate(your_list_of_list)}
Using the enumerate python built-in function allows you to get both the index of the nested list (i) and its value (nested_list).
From there, you can easily find the maximum of each nested list with the max function.
Finally, the index method allows you to find the first occurence of the maximum value from the nested list.

Index out of range Python NUmerical Iteration

I am a beginner in Python . While running the following code.
from array import *
x=[]
x[0]=.232
for i in range(25):
x[i+1]=1/[i+1]-5*x[i]
end
I get an error:
x[0]=.232 IndexError: list assignment index out of range
Can someone help me sort this out
Your code has more errors, but in this particular case you are trying to access the first position (x[0]) of an empty array (declared as x=[])
The same error appears in the loop (x[i+1] is index out of range since the array is empty) and you have a syntax error, end is not a python keyword. Finally, the body of the loop should be indented.
x=[] makes an empty list so you can't call x[0], so make a list of 26 elements(you need all total 26 elements) all equal to zero for convenience,
x=[0.0]*26
or
x=[0.0 for i in range(26)]
again [i+1] denotes a list and you cant do calculation with that make (i+1). also 1/(i+1) gives integer division make 1.0/(i+1)
end is not a valid python function here, dont use it indente the next line under the for loop. final programme,
x=[0.0]*26
x[0]=.232
for i in range(25):
x[i+1]=1.0/(i+1)-5*x[i]

Python error: IndexError: list assignment index out of range

a=[]
a.append(3)
a.append(7)
for j in range(2,23480):
a[j]=a[j-2]+(j+2)*(j+3)/2
When I write this code, it gives an error like this:
Traceback (most recent call last):
File "C:/Python26/tcount2.py", line 6, in <module>
a[j]=a[j-2]+(j+2)*(j+3)/2
IndexError: list assignment index out of range
May I know why and how to debug it?
Change this line of code:
a[j]=a[j-2]+(j+2)*(j+3)/2
to this:
a.append(a[j-2] + (j+2)*(j+3)/2)
You're adding new elements, elements that do not exist yet. Hence you need to use append: since the items do not exist yet, you cannot reference them by index. Overview of operations on mutable sequence types.
for j in range(2, 23480):
a.append(a[j - 2] + (j + 2) * (j + 3) / 2)
The reason for the error is that you're trying, as the error message says, to access a portion of the list that is currently out of range.
For instance, assume you're creating a list of 10 people, and you try to specify who the 11th person on that list is going to be. On your paper-pad, it might be easy to just make room for another person, but runtime objects, like the list in python, isn't that forgiving.
Your list starts out empty because of this:
a = []
then you add 2 elements to it, with this code:
a.append(3)
a.append(7)
this makes the size of the list just big enough to hold 2 elements, the two you added, which has an index of 0 and 1 (python lists are 0-based).
In your code, further down, you then specify the contents of element j which starts at 2, and your code blows up immediately because you're trying to say "for a list of 2 elements, please store the following value as the 3rd element".
Again, lists like the one in Python usually aren't that forgiving.
Instead, you're going to have to do one of two things:
In some cases, you want to store into an existing element, or add a new element, depending on whether the index you specify is available or not
In other cases, you always want to add a new element
In your case, you want to do nbr. 2, which means you want to rewrite this line of code:
a[j]=a[j-2]+(j+2)*(j+3)/2
to this:
a.append(a[j-2]+(j+2)*(j+3)/2)
This will append a new element to the end of the list, which is OK, instead of trying to assign a new value to element N+1, where N is the current length of the list, which isn't OK.
At j=2 you're trying to assign to a[2], which doesn't exist yet. You probably want to use append instead.
If you want to debug it, just change your code to print out the current index as you go:
a=[]
a.append(3)
a.append(7)
for j in range(2,23480):
print j # <-- this line
a[j]=a[j-2]+(j+2)*(j+3)/2
But you'll probably find that it errors out the second you access a[2] or higher; you've only added two values, but you're trying to access the 3rd and onward.
Try replacing your list ([]) with a dictionary ({}); that way, you can assign to whatever numbers you like -- or, if you really want a list, initialize it with 23479 items ([0] * 23479).
Python lists must be pre-initialzed. You need to do a = [0]*23480
Or you can append if you are adding one at a time. I think it would probably be faster to preallocate the array.
Python does not dynamically increase the size of an array when you assign to an element. You have to use a.append(element) to add an element onto the end, or a.insert(i, element) to insert the element at the position before i.

Categories

Resources