index error:list out of range - python

from string import Template
from string import Formatter
import pickle
f=open("C:/begpython/text2.txt",'r')
p='C:/begpython/text2.txt'
f1=open("C:/begpython/text3.txt",'w')
m=[]
i=0
k='a'
while k is not '':
k=f.readline()
mi=k.split(' ')
m=m+[mi]
i=i+1
print m[1]
f1.write(str(m[3]))
f1.write(str(m[4]))
x=[]
j=0
while j<i:
k=j-1
l=j+1
if j==0 or j==i:
j=j+1
else:
xj=[]
xj=xj+[j]
xj=xj+[m[j][2]]
xj=xj+[m[k][2]]
xj=xj+[m[l][2]]
xj=xj+[p]
x=x+[xj]
j=j+1
f1.write(','.join(x))
f.close()
f1.close()
It say line 33,xj=xj+m[l][2]
has index error,list out of range
please help
thanks in advance

Suppose i is 10 then on the last run of the while loop j is 9, now you have l = j + 1 so l will be 10 but your 10 lines in m are indexed 0..9 so m[l][2] will give an index error.
Also, you code would look a lot better if you just added the elements to your list in one go i.e:
x = x + [j, m[j][2], m[k][2], m[l][2], p]
Spaces are an eyes best friend!

The IndexError exception (list index out of range) means that you have attempted to access an array using an index that is beyond the bounds of the array. You can see this in action using a simple example like this:
>>> a = [1, 2, 3]
>>> a[2]
3
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
I can't exactly follow your code, but what that error means is that either:
l exceeds the bounds of m, or
2 exceeds the bounds of m[l]

Related

Trying to see if a number in a list is within 1 of its neighbour

I'm trying to compare all the numbers in this list and if any of them are within 1 of the number next to them in the list, if so then I want the command to print True. I realised that by applying the [x+1] to the last item in the list I'd be going out of the range of the list. I've tried to avoid this but I'm still getting the same error. Any help would be appreciated. Thanks :)
listed = [2,4,5,7]
for x in listed[:-1]:
if listed[x+1] - listed[x] == 1:
print(True)
else:
print(False)
IndexError Traceback (most recent call last)
Input In [155], in <cell line: 3>()
1 listed = [2,4,5,7]
3 for x in listed[:-1]:
----> 4 if listed[x+1] - listed[x] == 1:
5 print(True)
6 else:
IndexError: list index out of range
itertools.pairwise gives you nice neighboring pairs from a list that you can work with:
from itertools import pairwise
vals = [x for x in pairwise(listed) if abs(x[0] - x[1]) <= 1]
print(vals)
Output:
[(4, 5)]

How to find second runner up score?

n = int(input())
arr = map(int, input().split())
setA = set(arr)
for x in setA:
x.sorted()
print(x)
Here is the error that I am facing
5
9 8 7 4
Traceback (most recent call last):
File "C:\Users\jnnim\OneDrive\Desktop\hacker rank\practice\untitled1.py", line 6, in <module>
x.sorted()
AttributeError: 'int' object has no attribute 'sorted'
Requirements for the program
You are given n scores. Store them in a list and find the score of the runner-up.
The first line contains n elements. The second line contains an array of integers each separated by a space.
In this program for loop, I have tried that within setA, because we have to sort setA.
I had made the array in set because it does not keeps duplicate element.
Finally when I have to find out the runner up score then I will call [-1] index and make it print as runner up score.
If you need to know more about question please comment, I will tell you anything you need.
Please help me solve this error in this program only within these lines. Don't give a full solution
First off, it's sorted(x), not x.sorted. Second of all, you can sort a list, not a number.
You need to do this: x = sorted(setA).
This code will work:
n = int(input())
arr = map(int, input().split())
arrset = set(arr)
runnerup = 0
for index, val in enumerate(sorted(arrset), start=1):
if index == len(arrset) - 1:
runnerup = val
print(runnerup)
n = int(input())
arr = (int, input().split())
arrlist = []
for t in arr:
arrlist.append(t)
num=arrlist[1]
test_list = [int(i) for i in num]
test_sorted= (sorted(test_list, reverse=True))
List = []
for i in test_sorted:
if i != max(test_sorted):
List.append(i)
print(max(List))

Python - Trying to transfer data between nested lists (IndexError: list assignment index out of range)

I am aware of what it means to be out of range when indexing, but I am struggling to see why my code is generating this error...
import random
howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0, howMany):
newList[i] = oldList[random.randint(0, len(oldList)-1)] # subtract one
You are getting the error because newList is empty (its length is 0). You are trying to access elements in it using an index, but there are no indices. Here's a simpler example of what's happening:
>>> newList = []
>>> i = 0
>>> newList[i] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
What you want to do is use append():
import random
howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0,howMany):
newList.append(oldList[random.randint(0, len(oldList)-1)]) # subtract one

Python list as function argument

My goal is to try to return all the value in the list which has even position as well. The following is my python code. I don't know which part should I update. Please help!! Thanks
def evenValue(numbers):
results = []
for x in numbers:
if results.index(x) %2 ==0:
results.append(x)
return results
My error message is
> Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
evenValue([1,2,3,4,5,6])
File "<pyshell#6>", line 4, in evenValue
if results.index(x) %2 ==0:
ValueError: 1 is not in list
Try this. The slice takes even numbered elements.
def evenValue(numbers):
return numbers[0::2]
or shorter:
evenValue=lambda numbers: numbers[0::2]
def evenValue(numbers):
results = []
for x in numbers:
if numbers.index(x) %2 ==0: #Use 'numbers' list instead of 'results' list
results.append(x)
return results
print(evenValue([1,2,3,4,5,6,7]))
Output:
[1, 3, 5, 7]
Using list comprehension:
lst = list(range(50))
even_indexes = lambda numbers: [lst[i] for i in range(len(lst)) if i%2==0]
even_indexes(lst)

"list assignment index out of range" error when computing array

As you can see below, there is an array of arrays that saves the corners of the image. I want to use this array to calculate the length of each side.
This is my code:
imageDrawPoints = []
imageDrawPoints.append(imageShowConers)
imageSumPoints = []
i=0;
for imageDrawPoints in imageDrawPoints :
imageSumPoints[i] = imageDrawPoints[i] + imageDrawPoints[i+1]
i=i+1
print imageSumPoints
Error:
IndexError Traceback (most recent call
last) in ()
4 i=0;
5 for imageDrawPoints in imageDrawPoints :
----> 6 imageSumPoints[i] = imageDrawPoints[i] + imageDrawPoints[i+1]
7 i=i+1
8 print imageSumPoints
IndexError: list assignment index out of range
"imageDrawPoints[i+1]" is the problem.
If you have a list with 5 items it might look like [0,1,2,3,4]
When you get to the end of your iteration your code will be looking for:
imageDrawPoints[4+1]
which doesn't exist in your array and will throw the error.
Since I don't know what your code needs to do (you need to figure that out), but you need to add some condition looking for the end of the array and doing something alternative.
Something like:
listExample = [0,1,2,3,4]
counter = 0
for i in listExample:
if counter != len(listExample) -1:
print i
l = listExample[counter] + (listExample[counter+1])
else:
print "End Of Shape"
counter+=1

Categories