Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating quickly through list of tuples

Tags:

python

I wonder whether there's a quicker and less time consuming way to iterate over a list of tuples, finding the right match. What I do is:

# this is a very long list. my_list = [ (old1, new1), (old2, new2), (old3, new3), ... (oldN, newN)]  # go through entire list and look for match for j in my_list:     if j[0] == VALUE:         PAIR_FOUND = True         MATCHING_VALUE = j[1]         break 

this code can take quite some time to execute, depending on the number of items in the list. I'm sure there's a better way of doing this.

like image 847
memyself Avatar asked Apr 15 '13 17:04

memyself


People also ask

How do you iterate a list of tuples?

Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=' ' to print all items in a tuple in one line.

Why iteration in tuple is faster than list?

Tuples are immutable so, It doesn't require extra space to store new objects. Lists are allocated in two blocks: the fixed one with all the Python object information and a variable-sized block for the data. It is the reason creating a tuple is faster than List.

Which is faster list tuple or set?

Tuples are faster than lists. We should use a Tuple instead of a List if we are defining a constant set of values and all we are ever going to do with it is iterate through it. If we need an array of elements to be used as dictionary keys, we can use Tuples.

How does iterating over a tuple work?

We can initialize a tuple using the tuple(iterable) built-in function. We can iterate over tuples using a simple for-loop. We can do common sequence operations on tuples like indexing, slicing, concatenation, multiplication, getting the min, max value and so on.


1 Answers

I think that you can use

for j,k in my_list:   [ ... stuff ... ] 
like image 180
Eric Avatar answered Sep 21 '22 19:09

Eric