Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate a list of tuples

I'm looking for a clean way to iterate over a list of tuples where each is a pair like so [(a, b), (c,d) ...]. On top of that I would like to alter the tuples in the list.

Standard practice is to avoid changing a list while also iterating through it, so what should I do? Here's what I kind of want:

for i in range(len(tuple_list)):
  a, b = tuple_list[i]
  # update b's data
  # update tuple_list[i] to be (a, newB)
like image 840
Clev3r Avatar asked Feb 14 '13 17:02

Clev3r


2 Answers

Just replace the tuples in the list; you can alter a list while looping over it, as long as you avoid adding or removing elements:

for i, (a, b) in enumerate(tuple_list):
    new_b = some_process(b)
    tuple_list[i] = (a, new_b)

or, if you can summarize the changes to b into a function as I did above, use a list comprehension:

tuple_list = [(a, some_process(b)) for (a, b) in tuple_list]
like image 190
Martijn Pieters Avatar answered Oct 18 '22 23:10

Martijn Pieters


Why don't you go for a list comprehension instead of altering it?

new_list = [(a,new_b) for a,b in tuple_list]
like image 27
Udo Klein Avatar answered Oct 18 '22 22:10

Udo Klein