Reputation: 33
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
Reputation: 541
One way to do this:
new_list = [item for item in myList if item[0] == 1]
Upvotes: 3
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
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