rectangletangle
rectangletangle

Reputation: 53051

Using an index to get an item

I have a list in python ('A','B','C','D','E'), how do I get which item is under a particular index number?

Example:

Upvotes: 27

Views: 181324

Answers (6)

Nick Fraser
Nick Fraser

Reputation: 1

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.

Upvotes: 0

MrKulli
MrKulli

Reputation: 769

Same as any other language, just pass index number of element that you want to retrieve.

#!/usr/bin/env python
x = [2,3,4,5,6,7]
print(x[5])

Upvotes: 1

kiran siva sai
kiran siva sai

Reputation: 1

You can use pop():

x=[2,3,4,5,6,7]
print(x.pop(2))

output is 4

Upvotes: -6

Shameem
Shameem

Reputation: 2814

You can use _ _getitem__(key) function.

>>> iterable = ('A', 'B', 'C', 'D', 'E')
>>> key = 4
>>> iterable.__getitem__(key)
'E'

Upvotes: 4

Alex Martelli
Alex Martelli

Reputation: 882681

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.

Upvotes: 42

Martin Cote
Martin Cote

Reputation: 29892

values = ['A', 'B', 'C', 'D', 'E']
values[0] # returns 'A'
values[2] # returns 'C'
# etc.

Upvotes: 16

Related Questions