2
list = [('ba',4), ('hh',5), ('gg', 25)]

How do I do:

list.index('hh') ...and returns 1?

Then, how do I sort it by the 25, 5, 4?

What if I have 2 lists:

list1 = [('ba',4), ('hh',5), ('gg', 25)]
list2 = [('ja',40), ('hgh',88), ('hh', 2)]

how do I do a for each?

for item in l1:
    if item[0] in l2[0 of the tuple]:  
6
  • Not sure I understand your question from "What if I have 2 lists..." - What output do you expect? Commented Nov 29, 2009 at 11:25
  • It's ok, I got it. Your answer solves it. thanks a lot Commented Nov 29, 2009 at 11:26
  • 1
    Don't use keywords as variable names. It can lead to confusing bugs. Commented Nov 29, 2009 at 11:29
  • @Mark your point is well taken, but list is not a keyword. It is an identifier which has been assigned a value by the standard library. Commented Nov 29, 2009 at 11:37
  • 4
    Don't use identifiers which have been assigned values by the standard library as variable names. It can lead to confusing bugs. Don't use identifiers which shadow built-in functions as variable names. It can lead to confusing bugs. Commented Nov 29, 2009 at 12:45

8 Answers 8

5

First of, don't use list as the name for a variable, as it shadows the built-in list function.

  1. You can use enumerate to pair up list elements and their index:

    >>> l = [('ba',4), ('hh',5), ('gg', 25)]
    >>> [i for i, e in enumerate(l) if e[0] == 'hh']
    [1]
    
  2. For sorting you can use a lambda expression as shown by others, or you can pass an operator.itemgetter as the key argument to sorted:

    >>> from operator import itemgetter
    >>> sorted(l, key=itemgetter(1))
    [('ba', 4), ('hh', 5), ('gg', 25)]
    
  3. In-place sorting is also possible, using the sort method on lists:

    >>> l.sort(key=itemgetter(1))
    
Sign up to request clarification or add additional context in comments.

Comments

4

For the finding

>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> [ i for i,l in enumerate(L) if l[0] == 'hh' ][0]
1

You need to decide what to do if it is found multiple times or not at all - the above will throw IndexError if not found and return the first if it is found multiple times.

For the sorting

>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> sorted(L, key=lambda x: x[1])
[('ba', 4), ('hh', 5), ('gg', 25)]

Comments

2

I think Nick's sorting answer is good, but his find method unnecessarily iterates over the entire list, even after it has found a match. With a small change it can be fixed to stop iterating as soon as it finds the first element:

index = (i for i,l in enumerate(l) if l[0] == 'aa').next()

Or in Python 3:

index = next(i for i,l in enumerate(l) if l[0] == 'aa')

2 Comments

Note that for Python 3 this should be next(...) instead of (...).next().
next() throws StopIteration if 'aa' is not in the list.
1

to sort the list u can use a custom sort method some thing like this

x = [('ba',4), ('hh',5), ('gg', 25)]

def sortMethod(x,y):
    if x[1] < y[1]:return 1
    elif x[1] > y[1]:return -1
    else: return 0


print x         #unsorted
x.sort(sortMethod)
print x         #sorted

2 Comments

This sort method is much slower than the one shown by Nick Craig-Wood.
No downvoting - but this is not pythonic. See Nick's answer for the right way of doing this.
1

For the sort, you should use itemgetter

>>> import operator
>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> sorted(L, key=operator.itemgetter(1))
[('ba', 4), ('hh', 5), ('gg', 25)]

Comments

1

you can also have your list in dictionary form

list1 = [('ba',4), ('hh',5), ('gg', 25)]
dict1 = dict(list1)

print dict1['hh']
5

dicts are faster then list if you need to search like that.

btw, overriding built-in type list to variables are not good idea list = [('ba',4), ('hh',5), ('gg', 25)].

2 Comments

just a question .. isn't converting the list to dict will take time especially if it was a big list ?
of coz, but if he need to search multiple times, looping each items in list are not good for item retriving, dont you think so? building dict is normally one time, but for searching its very fast.
1
from itertools import imap

def find(iterable, item, key=None):
    """Find `item` in `iterable`.

    Return index of the found item or ``-1`` if there is none.

    Apply `key` function to items before comparison with
    `item`. ``key=None`` means an identity function.
    """
    it = iter(iterable) if key is None else imap(key, iterable)
    for i, e in enumerate(it):
        if e == item:
            return i
    return -1

Example:

L = [('ba', 4), ('hh', 5), ('gg', 25)]
print find(L, 'hh', key=lambda x: x[0])

Output:

1

Comments

0

For the last question, convert list2 into a set:

>>> list1 = [('ba',4), ('hh',5), ('gg', 25)]
>>> list2 = [('ja',40), ('hgh',88), ('hh', 2)]
>>> 
>>> wanted = set(a for (a,b) in list2)
>>> for x in list1:
...     if x[0] in wanted:
...         print x
... 
('hh', 5)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.