Using Index method in Tuple? - python

I understand Tuple are immutable and most of the list methods don't work on Tuple. Is there a way to find the index of an element in a tuple?(Other than typecasting it into a list and checking the index)

I don't quite see the problem:
>>> t = (1,2,3)
>>> t.index(2)
1

you can use index method of tuple to find the index of tuple.
>>> t = (1,2,3,4)
>>> t.index(2)
1
if tuple contains repetative items then use start and stop check.
t.index: (value, [start, [stop]])
>>> t = (1,2,3,4,2)
>>> t.index(2, 2, len(t))
4

Related

Tuple fails to print index if the item is repeated more than once

I am learning Python3 and I'm in tuples chapter now.
While we can use index method to print the place of an item like this:
>>> tup = ('a','b','a','c')
>>> tup.index('c')
>>> 3
But when I try to print the index for repeated item, it only prints for the first item and simply ignore the second one.
>>> tup.index('a')
0
I am expecting tuple to print both index (location).
Expected output
>>> tup.index('a')
0, 2
May I know why tuple having this behaviour? what if if we want to print the index for the repeated item in the tuple?
tuple.index is actually a three-argument function: tuple.index(x, start, end). It finds the first element equal to x in the range tuple[start:end]. It's just that by default start = 0 and end = len(t).
If you want the index of the second element you can do:
>>> i = tup.index('a')
>>> tup.index('a', i + 1)
2
If you want all indices you can use a list comprehension like L3viathan suggests.
Because that's what tuple.index does:
>>> help(tup.index)
index(...)
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
If you want all indices, you can make a list comprehension:
indices = [i for i, val in enumerate(tup) if val == 'c']
You can also do this with numpy.argwhere
https://docs.scipy.org/doc/numpy/reference/generated/numpy.argwhere.html
import numpy as np
np.argwhere(tup == 'a')

getting last element of a list of unknown size using slices

Let's say I have a list of unknown size, then I can access the last element using:
>>> l = list(range(10))
>>> l[-1]
9
However, is there any way to do this via a slice object like
>>> s = slice(-1, 10)
>>> l[s]
[9]
without knowing the length of my list?
Edit:
I simplified my Question a bit. I am fine with getting a list back, since I am iterating over the sublist later. I just needed a way of getting the last item of list besides being able to get every second element and so on ...
Yes, just use None as the end argument:
In [53]: l[slice(-1, None)]
Out[53]: [9]
This will of course produce a list [9], rather than the 9 in your question, because slicing a list always produces a sublist rather than a bare element.
If your objective is to pass arguments which you can use to index a list, you can use operator.itemgetter:
from operator import itemgetter
L = range(10)
itemgetter(-1)(L) # 9
In my opinion, for this specific task, itemgetter is cleaner than extracting a list via a slice, then extracting the only element of the list.
Note also that this works on a wider range of objects than just lists, e.g. with range as above.
If you were to access the last element of the list:
n = int(input())
user_input = [int(input) for i in range(n)]
last_element = user_input[-1]
Here we have used negative indices concept in lists.

Python: List containing tuple and integer

I have a list that is a combination of a tuple and integer
ex: K = [(7,8),8]
How do I access the first element of the tuple, 7?
I tried K[0[0]] and was not successful.
Try doing the following:
>>> k = [(7,8),8]
>>> k[0]
(7, 8)
>>> k[0][0]
7
Accessing element like this in a collection is wrong -
K[0[0]]
In this case, you are indexing the 0th element of 0 itself, which definitely causes an error. Try doing k[0][0]

Get last item from a list as integer/float

Very simple question, I have a list like so:
a = [0,1,2,3,4,5,7,8]
and I need to get the last item in that list as a float or an integer. If I do:
print a[0], a[4]
I get 1 5, which is fine, but if i try to retrieve the last item with:
print a[-1:]
I get the list [8] instead of the number 8. I know that I could just use print a[len(a)-1] but it feels kind of overkill and now I also have the doubt of why is a[-1:] returning a list instead of an element?
You need to do a[-1] to get the last item. See below:
>>> a = [0,1,2,3,4,5,7,8]
>>> a[-1]
8
>>>
Having the colon in there makes it slice the list, not index it.
Here are some references on lists and slicing/indexing them:
http://docs.python.org/2/tutorial/introduction.html#lists
Explain Python's slice notation
Just do:
>>> a = [0,1,2,3,4,5,7,8]
>>> a[-1]
8
You were slicing the list not getting last item.
Simplest way:
>>> a = [0,1,2,3,4,5,7,8]
>>> a[-1]
8
why is a[-1:] returning a list instead of an element?
>>> list[-1:] # returns list
[8]
>>> list[-1] # returns value
8
we also can use pop(). But it removes last element from the list.So it depends what you want to do.
list.pop()

How do I index a dictionary of multiple lists using a list of indexes?

I'm on Python 2.7.3.
If I have a dictionary of lists, like this:
>>> x1 = [1,2,3,4,5,6,7,8,5]
>>> x2 = range(11,20)
>>> mydict = {'first':x1,'second':x2}
... and the lists are equal size...
>>> len(mydict['second']) == len(mydict['first'])
True
How do I use a list of indexes like this:
>>> ind = [0,1,2,3,4,5,6,7]
To get the values from both lists in my dictionary? I have tried to use the "ind" list to index, but continuously get an error whether ind is a list or tuple like this:
>>> mydict['second'][ind]
TypeError: list indices must be integers, not set
I realize that the list isn't an integer, but each value in the set is an integer. Is there any way to get to the x1[ind] and x2[ind ] without iterating a counter" in a loop?
Don't know if it matters, but I have the index list already that I got from finding the unique values like this:
>>> import numpy as np
>>> ux1 = np.unique(x1, return_index = True)
You can use operator.itemgetter:
from operator import itemgetter
indexgetter = itemgetter(*ind)
indexed1 = indexgetter(mydict['first'])
indexed2 = indexgetter(mydict['second'])
note that in my example, indexed1 and indexed2 will be tuple instances, not list
instances. The alternative is to use a list comprehension:
second = mydict['second']
indexed2 = [second[i] for i in ind]
You want to use operator.itemgetter:
getter = itemgetter(*ind)
getter(mydict['second']) # returns a tuple of the elements you're searching for.

Categories

Resources