0

I have a list in Python,

a=[("title","artiste"),
   ("titl","artste"),
   ("ttle","titl")]

I want to create a second list; the second list should not include the search term.

How to search whether "titl" is in the first string of the tuples (just the first string, not the second string) of the three tuples or not?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Raiika
  • 109
  • 1
  • 11

1 Answers1

2

Use any() and a generator expression to determine whether the first ([0]) element of any of the tuples (t) in list a equal 'titl':

>>> any((t[0] == 'titl' for t in a))
True
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • thx for your fast response dude :3 I never thought about it xD – Raiika Apr 13 '14 at 03:37
  • Minor: the inner set of parentheses is unnecessary here. – DSM Apr 13 '14 at 03:37
  • @DSM: True. I figured that [Explicit is better than implicit.](http://legacy.python.org/dev/peps/pep-0020/) :-) – johnsyweb Apr 13 '14 at 03:39
  • 1
    @user3528188: Happy to help ☺︎ ︎︎ Note that this is a *list* of ***tuples***, not a *list* of *lists*. – johnsyweb Apr 13 '14 at 03:46
  • @Johnsyweb: what is it that you're being explicit about? There's no ambiguity here. – DSM Apr 13 '14 at 03:54
  • @DSM: You're right, it seems that there is no ambiguity and `any(t[0] == 'titl' for t in a)` is implicitly a [generator expression](https://wiki.python.org/moin/Generators) and will not be interpreted as a list comprehension. Because [`join()` performs better with list comprehesions](http://stackoverflow.com/a/9061024/78845), I've got into the habit of spelling out what I want. – johnsyweb Apr 13 '14 at 07:49