1

I'd like to loop over a list of tuples but having one of the indexes fixed with a determined value, like say we have this list:

myList = [(1,2,3) , (1,2,2), (2,3,4), (3,4,5), (1,3,4), (4,5,6), (4,6,8)]

and i wanted to loop over it fixing my first index with the value 1, so in the loop I would be accessing those, and only those, values:

[(1,2,3), (1,2,2), (1,3,4)]

I know I can do this:

    newList = []
    for item in myList:
        if item[0] == 1:
            newList.append(item)

and then loop over this new list, but is there a direct or more perfomatic way of doing this?!

Lexnard
  • 33
  • 5
  • Do you have to do this for the same list several times with different first-values? – kaya3 Jan 15 '20 at 19:45
  • 1
    Your way is as performant as it's going to get, it's an O(N) algorithm which is the best you can do. Are you actually seeing performance issues? – juanpa.arrivillaga Jan 15 '20 at 19:56
  • @juanpa.arrivillaga No, no, maybe I should had reformuled my question. Once I heard from a Profesor "If Python has something implemented then use it" (Maybe the best rephrase for english is "If Python has a built-in function for what you want, then use it"), so I was looking for a built-in method for that. – Lexnard Jan 15 '20 at 20:02

3 Answers3

3

One way to do this:

new_list = [item for item in myList if item[0] == 1]
chepner
  • 497,756
  • 71
  • 530
  • 681
myke
  • 479
  • 3
  • 14
1

You can also uso filter with a lambda. One benefit of this approach is that it returns a generator, so you do not need to instantiate the full filtered list (for example, if you only need the data to do subsequent processing).

>>> list(filter(lambda x: x[0] == 1, myList))
[(1, 2, 3), (1, 2, 2), (1, 3, 4)]
Alexander
  • 105,104
  • 32
  • 201
  • 196
  • 2
    In general, `filter` is not recommended. Same with `map`, these constructs are almost always better as list/dict/set comprehensions or generator expressions (and will be slightly faster usually). If you want lazy evaluation, you can use a generator expression. – juanpa.arrivillaga Jan 15 '20 at 19:54
  • I'm just highlighting another approach given that @myke already mentioned a conditional list comp. The topic of list comprehensions vs lambda + filter is discussed in detail here: https://stackoverflow.com/questions/3013449/list-comprehension-vs-lambda-filter – Alexander Jan 15 '20 at 20:00
0

Use list comprehension to simplify your code:

tuples = [(1,2,3) , (1,2,2), (2,3,4), (3,4,5), (1,3,4), (4,5,6), (4,6,8)]

filtered_tuples = [t for t in tuples if t[0] == 1]

for t in filtered_tuples:
    # code here
enbermudas
  • 1,603
  • 4
  • 20
  • 42