1

I have a list containing tuples with a standard format:

bar_list = [(bar1, bar2, bar3, bar4), (bar1, bar2, bar3, bar4), (bar1, bar2, bar3, bar4)...] 

Though I want to iterate through each tuple in the list and for each make specific modifications such as:

foo0 = bar1
foo1 = get_foo(foo0) #get_foo(var) being a function
foo2 = bar2
foo3 = bar3/2

And then repackage the revalued tuples in another list:

foo_list = [(foo1, foo2, foo3), (foo1, foo2, foo3), (foo1, foo2, foo3)...]

How could I accomplish this?

Alpine
  • 533
  • 1
  • 6
  • 18

2 Answers2

5

You could use a list comprehension:

foo_list = [(get_foo(bar1), bar2, bar3/2) 
            for bar1, bar2, bar3, bar4 in bar_list]

Note, I'm assuming you meant for foo1 to equal get_foo(bar1) rather than the NameError-raising and self-referential

foo1 = get_foo(foo1)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Thanks unutbu, worked to perfection (I ended up inserting the wrong variable, great assumption)! – Alpine May 02 '13 at 03:16
-1

You could use map here:

def func(lis):
    bar1,bar2,bar3,bar4=lis
    foo0 = bar1
    foo1 = get_foo(foo0) #or get_foo(bar1)
    foo2 = bar2
    foo3 = bar3/2
    return foo1,foo2,foo3


bar_list = [(bar1, bar2, bar3, bar4), (bar1, bar2, bar3, bar4), (bar1, bar2, bar3, bar4)...] 

foo_list = map(func,bar_lis)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Great, I think you missed to return `foo0` – eLRuLL May 02 '13 at 03:02
  • @eLRuLL OP's expected output has only 3 values: `(foo1,foo2,foo3)`. – Ashwini Chaudhary May 02 '13 at 03:03
  • Oh I didn't notice, this is perfect then. – eLRuLL May 02 '13 at 03:05
  • 1
    I wouldn't say perfect .. map considered unpythonic http://stackoverflow.com/q/5426754/674039 – wim May 02 '13 at 03:16
  • @wim `Unpythonic` doesn't means it is wrong and to be downvoted, and `map`,`filter` are still built-ins are py3.x. And there are cases where map outperforms LC's http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map. – Ashwini Chaudhary May 02 '13 at 04:00
  • @downvoter The downvoting arrow says "The answer is not useful"? Please explain how this is not useful. – Ashwini Chaudhary May 02 '13 at 04:02
  • I wasn't the downvoter in this case! Yet, I admit that I regularly downvote answers where `map` is recommended when an equivalent (and better) comprehension could be used instead. – wim May 02 '13 at 04:10
  • 1
    map outperforming LCs in some special cases is a non-issue for me, I always take style over performance - if it's performance-critical code, I'll put those parts in C – wim May 02 '13 at 04:12