Lexnard
Lexnard

Reputation: 33

Loop over List of tuples with one index of the tuple fixed

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?!

Upvotes: 1

Views: 424

Answers (3)

myke
myke

Reputation: 541

One way to do this:

new_list = [item for item in myList if item[0] == 1]

Upvotes: 3

Alexander
Alexander

Reputation: 109626

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)]

Upvotes: 1

enbermudas
enbermudas

Reputation: 1615

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

Upvotes: 0

Related Questions