Explicitly Select Items from a List or Tuple

Explicitly select items from a list or tuple

list( myBigList[i] for i in [87, 342, 217, 998, 500] )

I compared the answers with python 2.5.2:

  • 19.7 usec: [ myBigList[i] for i in [87, 342, 217, 998, 500] ]

  • 20.6 usec: map(myBigList.__getitem__, (87, 342, 217, 998, 500))

  • 22.7 usec: itemgetter(87, 342, 217, 998, 500)(myBigList)

  • 24.6 usec: list( myBigList[i] for i in [87, 342, 217, 998, 500] )

Note that in Python 3, the 1st was changed to be the same as the 4th.


Another option would be to start out with a numpy.array which allows indexing via a list or a numpy.array:

>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])

The tuple doesn't work the same way as those are slices.

List vs tuple, when to use each?

There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.

Pick from list of tuple combination pairs such that each tuple element appears at least twice

The easiest way to get each name exactly twice is the following, I guess:

lst = ["John", "Mike", "Mary", "Jane"]  # not shadowing 'list'

pairs = list(zip(lst, lst[1:]+lst[:1]))
pairs
# [('John', 'Mike'), ('Mike', 'Mary'), ('Mary', 'Jane'), ('Jane', 'John')]

This essentially circles the list and pairs each element with its two neighbours. If you need more randomness, you can shuffle the list beforehand or break up the list in chunks and apply this to the chunks.

How to get the first items from a list of tuples when each item is also wrapped in another tuple

Assuming this is Python, you can use a list comprehension. You will need to extract the first (only) value of the first element in each tuple:

res = [i[0][0] for i in test]

# ['over1.5', 'ht1over0.5', 'hgover0.5', 'over2.5', 'agover0.5']

I am trying to compare an item from a tuple and a list but get an error

Tuples are instantiated with parentheses but they are indexed with square-brackets, just like lists. Using parentheses conveys "calling" a function with the name of your variable before the parentheses, but obviously that variable name is a tuple, not a function name. That is why you are being told your tuple is not callable, because it isn't, though your code is trying to call it.

Check your conditional (if) statements and change the parentheses to square-brackets. It's a common and understandable mistake.

Finding match from a list of tuples

def f(lst, target):
return [t for t in lst if len(t) > len(target) and all(a == b for a, b in zip(t, target))]

so that:

f(x, ('a', 'b'))

returns:

[('a', 'b', 'c', 'd'), ('a', 'b', 'c')]

Using Python's list index() method on a list of tuples or objects?

How about this?

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [x for x, y in enumerate(tuple_list) if y[1] == 7]
[1]
>>> [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat']
[2]

As pointed out in the comments, this would get all matches. To just get the first one, you can do:

>>> [y[0] for y in tuple_list].index('kumquat')
2

There is a good discussion in the comments as to the speed difference between all the solutions posted. I may be a little biased but I would personally stick to a one-liner as the speed we're talking about is pretty insignificant versus creating functions and importing modules for this problem, but if you are planning on doing this to a very large amount of elements you might want to look at the other answers provided, as they are faster than what I provided.

Python selecting elements in a list by indices

Assuming you know what the indices to be selected are, it would work something like this:

indices = [1, 4, 7, 16, 19, 20]
templist = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]]
sublist = []

for i in indices:
sublist.append(templist[0][i])

This can also be expressed in the form of a list comprehension -

sublist = [templist[0][i] for i in indices]

Merge a list elements with tuple elements

Using the additional unpacking generalizations of modern (3.5+) Python, this isn't so hard:

merged = [(*i, x, *j) for i, x, j in zip(T1, L1, T2)]   

The tuples get unpacked with *, while the single element is just included normally in a tuple literal, no need to explicitly wrap the elements from L1 in a tuple, nor perform multiple concatenations producing intermediate temporary tuples.

Access multiple elements of list knowing their index

You can use operator.itemgetter:

from operator import itemgetter 
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)

Or you can use numpy:

import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]

But really, your current solution is fine. It's probably the neatest out of all of them.



Related Topics



Leave a reply



Submit