I have a list in python ('A','B','C','D','E'), how do I get which item is under a particular index number?
Example:
- Say it was given 0, it would return A.
- Given 2, it would return C.
- Given 4, it would return E.
What you show, ('A','B','C','D','E'), is not a list, it's a tuple (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.
So:
thetuple = ('A','B','C','D','E')
print thetuple[0]
prints A, and so forth.
Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0] etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.
You can use _ _getitem__(key) function.
>>> iterable = ('A', 'B', 'C', 'D', 'E')
>>> key = 4
>>> iterable.__getitem__(key)
'E'
When new to python and programming, I struggled with a means to edit a specific record in a list. List comprehensions will EXTRACT a record but it does not return an .index() in my_list. To edit the record in place I needed to know the .index() of the actual record in the list and then substitute values and this, to me, was the real value of the method.
I would create a unique list using enumerate():
>>> unique_ids = [[x[0], x[1][3]] for x in enumerate(my_list)]
>>>
Without getting into details about the structure of my_list, x[0] in the above example was the index() of the record whereas the 2nd element was the unique ID of the record.
for example, suppose the record I wanted to edit had unique ID "24672". It was a simple matter to locate the record in unique_ids
>>> wanted = [x for x in unique_ids if x[1] == "24672"][0]
>>> wanted
(245, "24672")
Thus I knew the index at the moment was 245 so I could edit as follows:
>>> my_list[245][6] = "Nick"
>>>
This would change the first name field in the my_list record with index 245.
>>> my_list[245][8] = "Fraser"
>>>
This would change the last name field in the my_list record with index 245.
I could make as many changes as I wanted and then write the changes to disk once satisfied.
I found this workable.
If anyone knows a faster means, I would love to know it.
myList[0]andmyList[1]? What happened why you tried something? Post the code you tried, please.