How do I say to the code to get the value 1 of the array within a while loop?
while line < 1000000:
userpass = passfile.readline().split()
line = line + 1
up = userpass[1]
print(userpass)
up = decode(TH3, up)
#See Values
#print (line)
#print (str(userpass))
#print (str(userEntry))
#Checking If Account Is Created
Traceback (most recent call last):
File "DataBase.py", line 55, in <module>
up = userpass[v]
IndexError: list index out of range
My error was that i did'nt append so the value userpass was replaced to a len of 2 to a len of 0 :
[] just added an if len > 0 :
before
Seems like userpass's length is less than 2.
In python, lists, tuples and dictionaries are 0-indexed. Meaning if you want to access the first element, you should write it like :
up = userpass[0]
Related
I am passing dot separated key as a argument. I have used split(".") and then print the value data. Here is my code:
desc = str(sys.argv[1])
st = desc.split(".")
i = 0
print (len(st))
for i in range(len(st)):
for ch in st:
st[i] = ch
print (st[i])
i += 1
print(i)
#print(data[st1][st2]..[stn])
I am getting the output as
3
db
1
dap
2
nodes
3
db
2
db
3
Traceback (most recent call last):
File "getvar.py", line 17, in <module>
st[i] = ch
IndexError: list assignment index out of range
I want the data[db][dap][nodes] which will give me the correct value. How should I proceed?
You are confusing 2 loops : for item in items and for i in range.
When you use i in range the max value in length -1 because indexes are zero based.
when you have used split st is an array of values so the line st[i] = ch is reloading the value back where is was read from.
Here I give both syntaxes of the loop. You will observe that print(st) before the loops gives the result that you want.
desc="10.12.45.35.66.28"
#desc = str(sys.argv[1])
st = desc.split(".")
print([st])
print ("length:",len(st))
for j in range(len(st)-1):
print (j," -> ", st[j])
i = 0
for ch in st:
st[i] = ch
print (i," -> ", st[i])
i += 1
I am trying to remove a value from the list but python seems to not be able to even though I am able to print it. The value is 5 which you will be able to see in the error but when I try to remove the same value it throws me an error message.
The "sequence.remove(e+1)" line should be the same value as "print(sequence[e+1])" right?
code:
def solution(sequence):
decisionList = []
ultDec = bool
def comparing():
i = 0
decisionList.clear()
for i in range(len(sequence)-1):
num1 = i
num2 = i + 1
if sequence[num1] < sequence[num2]:
decisionList.append("bigger")
if sequence[num1] > sequence[num2]:
decisionList.append("smaller")
if sequence[num1] == sequence[num2]:
decisionList.append("equal")
findIrregular()
repeated = 0
def findIrregular():
nonlocal repeated
ultDec = ""
e = 0
for e in range(len(decisionList)):
val1 = e
if decisionList[val1] == "smaller":
if repeated < 1:
print(sequence[e+1], "is the value im trying to remove")
sequence.remove(e+1)
repeated = repeated + 1
comparing()
if repeated >= 1:
return False
elif decisionList[val1] == "equal":
if repeated < 1:
sequence.remove(e + 1)
repeated = repeated + 1
comparing()
if repeated >= 1:
return False
elif decisionList[val1] == "bigger":
pass
return True
comparing()
return findIrregular()
solution([3, 6, 5, 8, 10, 20, 15])
error:
So as you can see "5 is the value im trying to remove" is what causes the error
5 is the value im trying to remove
Traceback (most recent call last):
File "<string>", line 46, in <module>
File "<string>", line 44, in solution
File "<string>", line 16, in comparing
File "<string>", line 29, in findIrregular
ValueError: list.remove(x): x not in list
list.remove removes the given member of the list, for example, if we have a list like [1, 2, 5] and we use .remove(5) our list will be [1, 2].
If you want to remove a member by its index, try .pop(i)
Well, remove takes the item/value you want to remove. If you want to remove by index then use .pop(index)
Instead of this:
sequence.remove(e+1)
Use:
sequence.pop(e+1)
you can use
sequence.remove(sequence[e+1])
or
sequence.pop(e+1)
here is my code :
if __name__ == '__main__':
n = int(input())
for i in range(n):
name = input()
score = float(input())
python_students = [[name, score]]
z=len(python_students)
for i in range(z):
if python_students[i][1]<python_students[i+1][1]:
list = [python_students[1]]
list.sort()
print(list)
error : Traceback (most recent call last):
File "solution.py", line 9, in <module>
if python_students[i][1]<python_students[i+1][1]:
IndexError: list index out of range
i am literally confused with this type of error , kindly explain and help me with this code.
i am trying to fetch names in alphabetical order from the list
z should be len(python_students)-1. At the last iteration, python_students[i+1][1] goes outside the bounds of the list.
Below is simplifed code, your code has lots of loopholes. you shouldn't use list to store list elements, since list is build class provided by python. its not good practice. also use append to append elements into the list.
if __name__ == '__main__':
python_students = []
n = int(input())
for i in range(n):
name = input()
score = float(input())
python_students.append([name,score])
#python_students = [[name, score]]
z=len(python_students) - 1
p_s = []
for i in range(0,z):
if python_students[i][1]<python_students[i+1][1]:
p_s.append(python_students[1])
p_s.sort()
print(p_s)
I am trying to find averages from a text file. The text file has columns of numbers and I want to find the average of each column. I get the follwoing error:
IndexError: list index out of range
The code I am using is:
import os
os.chdir(r"path of my file")
file_open = open("name of my file", "r")
file_write = open ("average.txt", "w")
line = file_open.readlines()
list_of_lines = []
length = len(list_of_lines[0])
total = 0
for i in line:
values = i.split('\t')
list_of_lines.append(values)
count = 0
for j in list_of_lines:
count +=1
for k in range(0,count):
print k
list_of_lines[k].remove('\n')
for o in range(0,count):
for p in range(0,length):
print list_of_lines[p][o]
number = int(list_of_lines[p][o])
total + number
average = total/count
print average
The error is in line
length = len(list_of_lines[0])
Please let me know if I can provide anymore information.
The issue is you are trying to get the length of something in the array, not the array itself.
Try this:
length = len(list_of_lines)
You wrote length = len(list_of_lines[0])
line_of_lines is defined right above this line, as a list with 0 items in it. As a result, you cannot select the first item (index number 0) because index number 0 does not exist. Therefore, it is out of range.
I have recently started to learn python. The following code is throwing type error stating that I can't use tuples as index in a list. I am quite sure I am using integers and not list to access to access my list. The error is thrown at the line where I build a sub-matrix. Can you help me out?
Traceback (most recent call last):
File "matrix_input.py", line 44, in <module>
print(contains(matrix, target))
File "matrix_input.py", line 33, in contains
sub_matrix = [row[index:len(target[0])] for row in matrix[i, len(target)]]
TypeError: list indices must be integers, not tuple
This is the function throwing the error:
def sub_array(row, sub_row):
i = 0
index = -1
for idx, val in enumerate(row):
if i >= len(sub_row):
break
elif val == sub_row[i]:
index = idx
i+=1
else:
i = 0
return index if i == len(sub_row) else -1
def contains(matrix, target):
for i in range(len(matrix)):
index = sub_array(matrix[i], target[0])
if index is not -1:
sub_matrix = [row[index:len(target[0])] for row in matrix[i, len(target)]]
print(sub_matrix)
if sub_matrix == target:
return "YES"
return "NO"
matrix[i, len(target)] attempts to access an item in matrix with the tuple i, len(target) as an index – not an integer. It appears you intended to use matrix[i][len(target)] instead.
You should compare integers with ==/!=, too – index != -1 instead of index is not -1.