Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Say it was given 0, it would return A.
  • Given 2, it would return C.
  • Given 4, it would return E.
like image 607
rectangletangle Avatar asked Jun 11 '10 02:06

rectangletangle


People also ask

Which function is used to get the index value of an element?

The INDEX function returns a value or the reference to a value from within a table or range.

Can you index into a list Python?

Note. python lists are 0-indexed. So the first element is 0, second is 1, so on.


1 Answers

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.

like image 162
Alex Martelli Avatar answered Oct 28 '22 13:10

Alex Martelli