views:

97

answers:

7

Hey,

Does a direct way to do this exists?

if element in aList:
   #get the element from the list

I'm thinking something like this:

aList = [ ([1,2,3],4) , ([5,6,7],8) ]
element = [5,6,7]
if element in aList
     #print the 8
+1  A: 

(Note: this answer refers to the question text, not the example given in the code, which doesn't quite match.)

Printing the element itself doesn't make any sense, because you already have it in the test:

if element in lst:
    print element

If you want the index, there's an index method:

if element in lst:
    print lst.index(element)

And, on the off chance that you're asking this because you want to loop through a list and do things with both the value and the index, be sure to use the enumerate idiom:

for i, val in enumerate(lst):
  print "list index": i
  print "corresponding value": val
Vicki Laidler
The delete link is right above the comments, to the left side (just to the right of the votes).
Roger Pate
@Roger: huh, I see link/edit/flag just above the comments, but no delete. Maybe because I'm not registered? Anyway I decided to restore the answer since someone had already upvoted it, but with a caveat as not quite on point; but thanks.
Vicki Laidler
@Vicki: It might be because of registration, and I'd rather some answers restored with a note than edit-wiped, just trying to help since you said you couldn't find it.
Roger Pate
A: 
>>> aList = [ ([1,2,3],4) , ([5,6,7],8) ]
>>> for i in aList:
...     if [5,6,7] in i:
...          print i[-1]
...
8
ghostdog74
+1  A: 
>>> aList = [ ([1,2,3],4) , ([5,6,7],8) ]
>>> element = [5,6,7]

if you only wish to check if the first element is present

>>> any(element==x[0] for x in aList)
True

to find the corresponding value

>>> next(x[1] for x in aList if element==x[0])
8
gnibbler
This doesn't show how to get the "corresponding value", which is 8 in this case. (At least it didn't until you edited :P)
Roger Pate
@Roger, that was the answer to the first part of the question
gnibbler
+3  A: 
L = [([1, 2, 3], 4), ([5, 6, 7], 8)]
element = [5, 6, 7]

for a, b in L:
  if a == element:
    print b
    break
else:
  print "not found"

But it sounds like you want to use a dictionary:

L = [([1, 2, 3], 4), ([5, 6, 7], 8)]
element = [5, 6, 7]

D = dict((tuple(a), b) for a, b in L)
# keys must be hashable: list is not, but tuple is
# or you could just build the dict directly:
#D = {(1,2,3): 4, (5,6,7): 8}

v = D.get(tuple(element))
if v is not None:
  print v
else:
  print "not found"

Note that while there are more compact forms using next below, I imagined the reality of your code (rather than the contrived example) to be doing something at least slightly more complicated, so that using an block for the if and else becomes more readable with multiple statements.

Roger Pate
@gnibbler: Thanks for the correction, though I'd rather appreciate a comment that soon after an edit, like within the first 5 mintutes as it was here.
Roger Pate
@Roger, sorry I figured it was just a minor oversight
gnibbler
@gnibbler: I often go through rapid iterations, as I review how a question reads from multiple perspectives, etc.; in this case I got a warning "this post has been edited by someone else".
Roger Pate
Don't search manually. Use list.index and catch ValueError. It's a builtin, so it's much faster, and it's much clearer to use the method eveyone already knows than to roll your own.
Glenn Maynard
@Glenn: Doesn't apply in this case. Regardless, the dict solution will be faster than either, and it sounds like a dict is really what the OP wants.
Roger Pate
A: 

[5, 6, 7] is not an item of the aList you show, so the if will fail, and your question as posed just doesn't pertain. More generally, the loop implied in such an if tosses away the index anyway. A way to make your code snippet work would be, instead of the if, to have something like (Python 2.6 or better -- honk if you need to work on different versions):

where = next((x for x in aList if x[0] == element), None)
if where:
  print(x[1])

More generally, the expressions in the next and in the print must depend on the exact "fine grained" structure of aList -- in your example, x[0] and x[1] work just fine, but in a slightly different example you may need different expressions. There is no "generic" way that totally ignores how your data is actually structured and "magically works anyway"!-)

Alex Martelli
A: 

One possible solution.

aList = [ ([1,2,3],4) , ([5,6,7],8) ]
element = [5,6,7]

>>> print(*[y for x,y in aList if element == x])
8
TheMachineCharmer
`SyntaxError: can use starred expression only as assignment target`
Roger Pate
@Roger Pate:I removed `print` for clarity but it didn't work. Corrected now. Thanks. Any other improvements?? :)
TheMachineCharmer
Just use `[...][0]`; however, the others answers with *next* and an generator are clearer (at least for me), allow for a default value if your list would be empty, and only require iterating *aList* until the first match is found. Additionally, what you have now is only valid in Python 3.x, but you would print multiple values if present and that's desired.
Roger Pate
A: 

The code in your question is sort of weird. But, assuming you're learning the basics:

Getting the index of an element:

it's actually simple: list.index(element). Assuming of course, the element only appears once. If it appears more than once, you can use the extra parameters:

list.index(element, start_index): here it will start searching from start_index. There's also:
list.index(element, start_index, end_index): I think it's self explanitory.

Getting the index in a for loop

If you're looping on a list and you want to loop on both the index and the element, the pythonic way is to enumerate the list:

for index, element in enumerate(some_list):
    # here, element is some_list[index]

Here, enumerate is a function that takes a list and returns a list of tuples. Say your list is ['a', 'b', 'c'], then enumerate would return: [ (1, 'a'), (2, 'b'), (3, 'c') ]

When you iterate over that, each item is a tuple, and you can unpack that tuple.

tuple unpacking is basically like this:

>>> t = (1, 'a')
>>> x, y = t
>>> t
(1, 'a')
>>> x
1
>>> y
'a'
>>> 
hasen j
list.index is not applicable here, as the searched-for item is not directly in the list.
Roger Pate