Index of element in an array in Python - 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.

Related

Sorting list of strings by a character

I got the following assignment:
For a given list of strings write a function that returns a sorted list with all strings starting with the character x at the beginning (define two lists)
I stuck here:
set_words_list = ["argentinax", "football", "ss", "poxland", "axmerica"]
set_words_list.sort(key=str("x"))
print(set_words_list)
And then error pops out:
Traceback (most recent call last):
File "/5SortList/main.py", line 7, in <module>
set_words_list.sort(key=str("x"))
TypeError: 'str' object is not callable
It is my first time coding in Python, and I have no clue where to go from there.
On top of that, according to the task one needs to use 2 lists, yet I don't know how it can help me.
The simplest way is to split the input into two lists. One contains the elements that start with x, the other contains the rest. That's what the instructions meant by "define two lists".
Then sort each of these lists and concatenate them.
x_words = []
nox_words = []
for word in set_words_list:
if word.startswith("x"):
x_words.append(word)
else:
nox_words.append(word)
result = sorted(x_words) + sorted(nox_words)
list.sort(reverse=True|False, key=myFunc)
reverse --> Optional. reverse=True will sort the list descending. Default is reverse=False
key--> Optional. A function to specify the sorting criteria(s)
In below code we are passing myFunc to the key part of the sort function.
Function returns not e.startswith('x') since True == 1. This will sort the words starting with 'x'.
def myFunc(e):
return not e.startswith('x')
set_words_list = ["argentinax", "football", "ss", "poxland", "axmerica", 'xx']
set_words_list.sort(key=myFunc)
print(set_words_list)
set_words_list = ["argentinax", "football", "ss", "poxland", 'xamerica' ,"axmerica"]
x_first_letter = sorted([x for x in set_words_list if x[0]=='x'])
nox_first_letter = sorted([x for x in set_words_list if not x[0]=='x'])

IndexError: list assignment index out of range - python

I have a problem with my code, I just want to write the result in csv and i got IndexError
seleksi = []
p = FeatureSelection(fiturs, docs)
seleksi[0] = p.select()
with open('test.csv','wb') as selection:
selections = csv.writer(selection)
for x in seleksi:
selections.writerow(selections)
In p.select is:
['A',1]
['B',2]
['C',3]
etc
and i got error in:
seleksi[0] = p.select()
IndexError: list assignment index out of range
Process finished with exit code 1
what should i do?
[], calls __get(index) in background. when you say seleksi[0], you are trying to get value at index 0 of seleksi, which is an empty list.
You should just do:
seleksi = p.select()
When you initlialize a list using
seleksi = []
It is an empty list. The lenght of list is 0.
Hence
seleksi[0]
gives an error.
You need to append to the list for it to get values, something like
seleksi.append(p.select())
If you still want to assign it based on index, initialize it as array of zeros or some dummy value
seleksi = [0]* n
See this: List of zeros in python
You are accesing before assignment on seleksi[0] = p.select(), this should solve it:
seleksi.append(p.select())
Since you are iterating over saleksi I guess that what you really want is to store p.select(), you may want to do seleksi = p.select() instead then.
EDIT:
i got this selections.writerow(selections) _csv.Error: sequence
expected
you want to write x, so selections.writerow(x) is the way to go.
Your final code would look like this:
p = FeatureSelection(fiturs, docs)
seleksi = p.select()
with open('test.csv','wb') as selection:
selections = csv.writer(selection)
for x in seleksi:
selections.writerow(x)

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.

Python List Index out of Range when Appending a List

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

how to make my list to append different type data in python?

The list in python can load different type of data.
>>> x=[3,4,"hallo"]
>>> x
[3, 4, 'hallo']
How can i define a multi-dim list to load different type of data?
>>> info=['']*3
>>> info[0].append(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
I want to make info to be a multi-dim list,info[0] can load character and number.
Create an empty list of lists first:
info = [[] for _ in range(3)]
info[0].append(2)
info[1].append("test")
info will then look like:
[[2], ['test'], []]
Quite simply you are trying to append to a string that happens to be contained in a list. But you can't append to a string (string concatenation is something else). So either use string concatenation (if that was what you intended), or use an empty list as a container inside the list.
l = [[],[]]
is a list with two elements, two empty lists.
l.append('something')
gives you
[[],[],'something']
but l[0].append('something') would have given you:
[['something'],[]]
Instead of append, do it as follows:
>>> info=['']*3
>>> info[0] += '2' #if you want it stored as a string
Or
>>> info[0] = int(info[0]+'2') #if you want it stored as an int

Categories

Resources