Python: List containing tuple and integer - python

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]

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.

Replace first elements of tuple with zero over a certain length

I have a sorted list based on first element:
A = [(0.11, '201405'), (0.41, '201402'),.....,(1.5, '201430')] # values and time
and want to change first element of each tuple:
x = len(C) # C is a list and its length is 2
y = len(D) # D is a list and its length is 1
if x > y:
A[0[0:x]] = 0.0 # if x > y then set first element of A equal to zero (over length of C)
But I get following error:
TypeError: 'int' object is not subscriptable
Please suggest to fix it.
If I understand your question correctly, you want to replace the first element in each of the first few tuples with 0. Tuples are not modifyable, so you can not modify the existing tuples in the list, but you have to create a new list, holding new tuples. You can do this using a list comprehension.
Example:
>>> A = [(1,"a"), (2,"b"), (3,"c"), (4,"d")]
>>> A = [(x if i > 1 else 0, y) for i, (x, y) in enumerate(A)]
>>> print A
[(0, 'a'), (0, 'b'), (3, 'c'), (4, 'd')]
This will enumerate all the entries in the list, and for each entry create a tuple with the first element being 0, if the index i of that entry is lower than some threshold, or the original value otherwise.
As iharob mentioned, you have a subscript notation error.
Tuples are immutable. You can't just replace 1 element of the tuple in your list. You have to replace the whole tuple with another tuple containing 0.0 as first value and the existing second value. Note that lists are modifiable but tuples aren't. That's why you can update the list A, but you have to replace the tuple with a new tuple.
Here's an example that does not recreate the whole list:
for i, t in enumerate(A):
if i < 1:
A[i] = (0, t[1])
You have an error in A[0[0:x]] = 0.0 you are using subscript notation for the number 0.
Furthermore, the tuple is an immutable type. Hence, it is impossible to change the content of a tuple. You'd better to generate a new list such as:
A = [0.0]+A[1:]

Using Index method in Tuple?

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

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()

Categories

Resources