Hi all,

Had a simple problem that turned into an interesting solution and I
thought I would share it here.

I had a list of tuples that I needed to get the first value from and
generate a list.

tuple_list = (
    ('John', 'Doe'),
    ('Mark', 'Mason'),
    ('Jeff', 'Stevens'),
    ('Bat', 'Man')
  )

# what I'd do in C or other procedural languages
result_list = []
for item in tuple_list:
    result_list.append(item[0])

# the first Pythonic attempt using comprehensions
result_list = [x[0] for x in tuple_list]

# the final functional way
[result_list, _] = zip(*tuple_list)

I really like how Python allows me to do what I feel is the most
natural solution (for a seasoned procedural programmer) while allowing
a satisfying path towards a more functional approach.

Cheers,
James
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to