Reputation: 13
For each object in my Python list, I want to define an integer which is the first index of the object:
firstindex( some object ) = mylist.index( some object)
How do I make such a definition for all objects simultaneously?
I tried doing this:
firstindex = []
i=1
while i < 100 :
firstindex.append( mylist.index("i") )
i=i+1
But it tells me that 'i' is not in the list. However the list is of the form [1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,....]
Upvotes: 0
Views: 63
Reputation: 151
Why don't you just use a dictionnary?
d = dict() # or d = {}
for i in range(100):
d['firstindex_'+str(i)] = ""
This would create a dictionnary of size 100 with all values as empty strings. You can access it with d['firstindex_0'] through d['firstindex_99'].
Upvotes: 1
Reputation: 710
You should change your code to the following:
firstindex = []
i= 1
while i < 100 :
firstindex.append( mylist.index(str(i)) )
i=i+1
Your previous code searched for an item in the list with the value "i" which is the string "i". You instead want to search for the value of the variable i which is the string "1" then "2" then "3" and so on. So you should simply search for the index of str(i).
Str(i)
returns a string of the value in i.
Upvotes: 1
Reputation: 16224
That's because the funct list.index(obj) return the index of the object in the list.
>>> ["foo", "bar", "baz"].index("bar")
1
And your list "mylist"
is a list of object that may not content the index "i"
, that is a String
Upvotes: 0