Python List Index out of Range when Appending a List - python

When appending to a list in Python, I am getting the error:
Traceback (most recent call last):
File "/Volumes/HARDRIVE/Java/Python/Test.py", line 16, in <module>
cities.append([1][i])
IndexError: list index out of range
The list cities is initialized here:
cities = [[0 for x in range(math.factorial(CITIES)+3)] for x in range(math.factorial(CITIES)+3)]
Why is it producing this error when there is obviously enough space for the append operation (I gave the list three more than it needed)? What should I do to fix it? This is the loop that contains the line of code:
for i in range(0,CITIES):
cities.append([1][i])
cities.append([1][i])
holder=cities[0][i]
cities[0][i]=cities[CITIES+1][i]
cities[CITIES+1][i]=holder
Thanks

I think maybe you might want to append a new list onto your existing lists
cities.append([1,i,0])
as an aside you can reproduce the issue easily as mentioned in the comments without anything to do with appending
for i in range(3):
try: print i, [1][i]
except IndexError: print "LIST:[1] has no index", i

Related

accessing nested dictionaries when you know the nested key?

This one is probably pretty easy, but I can't figure it out! Suppose I have a dictionary with a nested dictionary, that I know the nested dictionary key that I can store in a variable, how would I access this value?
k = 'mynested'
nestedk = 'blah'
x = {}
x['mynested'] = {}
x['mynested']['blah'] = 1
print(x[k[nestedk]])
throws error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
There is a slight mistake in your last line print(x[k[nestedk]]). This line actually means that you are treating the k variable as a list which is actually a string and the characters of the string can only be accessed by an integer index and not by a string index.
Change the last line to the below
print(x[k][nestedk])
You can get it with x[k][nestedk]. You can access the values similar to assigning values inside dictionary. As you are assigning
X[k] = {}
and x[k][nestedk] = 1
The value is 1 and key for nested object is k so initially we get the inner dictionary by x[k] and then we get the value using nested key in your case nestedk.
Thus you have to correct your print statement like below
print(x[k][nestedk])

Index of element in an array in Python

I'm trying to display indices of an array in a for loop in Pyrhon.
Here is my code:
computerPlayersList = [nbr]
For computerPlayer in computerPlayersList:
print(computerPlayersList.index(computerPlayer))
But this is not working ? What's the correct displaying method please ? Thank you
In python, keywords must be written in lowercase. Use for, not For:
computerPlayersList = [5, 3, 9, 6]
for computerPlayer in computerPlayersList:
print(computerPlayersList.index(computerPlayer))
returns
0
1
2
3
Code :
computerPlayersList = [10,20,30]
for counter,computerPlayer in enumerate(computerPlayersList):
print(counter,computerPlayer)
using enumerate is also a great option. the counter variable will be having the index value of each item.
Output :
0 10
1 20
2 30
You can use the enumerate() method for index and the value in the following manner:
for index,computerPlayer in enumerate(computerPlayersList):
print (index,computerPlayer)
Firstly "For" lower case since it's a keyword.
computerPlayersList = ["nbr","abc"]
for computerPlayer in computerPlayersList:
print(computerPlayersList.index(computerPlayer))
or
computerPlayersList = [10,20,30]
for computerPlayer in computerPlayersList:
print(computerPlayersList.index(computerPlayer))
The elements in the list are either string or integer/float so list cannot have variable names.
>>> a=10
>>> b=[]
>>> c=b[a]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
I'm guessing that you are giving variable names inside the list.
So there are two errors, next time post that error message so that we can see what exactly is the problem.

List index out of range error list reduced while iteration

I think I'm getting an error because the range of the list is reduced during iteration of the loop. I have 95 nested lists within a large list mega4, and I'm trying to delete some strings with if and else. The list ufields consist of 18 strings.
>>> for i in range(len(mega4)):
... for j in range(len(mega4[i])):
... for f in ufields:
... if (f in mega4[i][j]) is False:
... mega4[i].remove(mega4[i][j])
... else:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
IndexError: list index out of range
The fourth line is basically asking if each element within mega4[i] has each strings within ufields, how can I remove the mega4[i][j] in this case?
Edit:
I followed comments below and tried building a new list but this one does not seem to work
>>> mega5 = []
>>> for i in range(len(mega4)):
... for f in ufields:
... mega5.append([x for x in mega4[i] if f in x is True])
len(mega5) is larger than len(mega4) whereas it should be the same.
Depending on how ufields is defined, you could eliminate the innermost loop by using if mega4[i][j] in ufields.
Instead of modifying mega4 within this loop, you could build up a list of what elements you want to eliminate, and then do the actual elimination afterwards (looping over your list of candidates instead of mega4 itself).
Simpler way:
result = [[sub for sub in item if sub] for item in mega4]
Your way wasn't working because you were editing list while iterating over it.

in my for loop .split() only works once

So I have this app. It records data from the accelerometer. Here's the format of the data. It's saved in a .csv file.
time, x, y, z
0.000000,0.064553,-0.046095,0.353776
Here's the variables declared at the top of my program.
length = sum(1 for line in open('couchDrop.csv'))
wholeList = [length]
timeList = [length]#holds a list of all the times
xList = [length]
yList = [length]
zList = [length]
I'm trying to create four lists; time, x, y, z. Currently the entire data file is stored in one list. Each line in the list contains 4 numbers representing time, x, y, and z. I need to split wholeList into the four different lists. Here's the subroutine where this happens:
def easySplit():
print "easySplit is go "
for i in range (0, length):
current = wholeList[i]
current = current[:-2] #gets rid of a symbol that may be messing tings up
print current
print i
timeList[i], xList[i], yList[i], zList[i] = current.split(',')
print timeList[i]
print xList[i]
print yList[i]
print zList[i]
print ""
Here's the error I get:
Traceback (most recent call last):
File "/home/william/Desktop/acceleration plotter/main.py", line 105, in <module>
main()
File "/home/william/Desktop/acceleration plotter/main.py", line 28, in main
easySplit()
File "/home/william/Desktop/acceleration plotter/main.py", line 86, in easySplit
timeList[i], xList[i], yList[i], zList[i] = current.split(',')
IndexError: list assignment index out of range`
Another weird thing is that my dot split seems to work fine the first time through the loop.
Any help would be greatly appreciated.
For data manipulation like this, I'd recommend using Pandas. In one line, you can read the data from the CSV into a Dataframe.
import pandas as pd
df = pd.read_csv("couchDrop.csv")
Then, you can easily select each column by name. You can manipulate the data as a pd.Series or manipulate as a np.array or convert to a list. For example:
x_list = list(df.x)
You can find more information about pandas at http://pandas.pydata.org/pandas-docs/stable/10min.html.
EDIT: The error with your original code is that syntax like xList = [length] does not create a list of length length. It creates a list of length one containing a single int element with the value of length.
the code line wholeList = [length] doesnt create a list of length = length. It creates a list with only one element which is integer length, so if you were to print(wholeList) you will only see [3]
Since lists are mutable in python, you can just to wholeList =[] and keep appending elements to it. It doesnt have to be of specific length.
And when you do current.split(',') which is derived from wholeList, its trying to split only data available for first iteration i.e. [3]

How to remove the following error?

The question was to find the symmetric difference between two sets without using the the corresponding method !
from future import print_function
M=int(raw_input())
X=map(int,raw_input().split())
N=int(raw_input())
Y=map(int,raw_input().split())
mys=set()
mys1=set()
for i in X:
mys.add(i)
for i in Y:
mys1.add(i)
un=mys.union(mys1)
inx=mys.intersection(mys1)
sd=un.difference(inx)
w=list(sd)
w=w.sort()
for i in (w):
print(w[i],end=' ')
Error occured is:
Traceback (most recent call last): File "hackset.py", line 18, in
<module>
for i in len(w): TypeError: object of type 'NoneType' has no len()**
list.sort does not return a new sorted function. It just sort the list (return None).
If you want to get a new list sorted, use sorted instead.
There's another issue. Iterating a list yields elements, you don't need to index them to get items; Just iterate without indexing.
for item in w:
print(item, end=' ')
Your error is here:
w=w.sort()
The return type for w.sort() is 'None'. The sort() method is in-place. Change it to just:
w.sort()

Categories

Resources