473,413 Members | 1,799 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

Moving to functional programming

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
Jul 11 '08 #1
10 960
James Fassett:
# 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.
The list comprehension is quite more readable to me, so I suggest you
to use it. It's probably the default way to do it in Python.

If you want functional code this is another way (I have not tested the
relative performance but it may be quick):
>>tuple_list = (
.... ('John', 'Doe'),
.... ('Mark', 'Mason'),
.... ('Jeff', 'Stevens'),
.... ('Bat', 'Man')
.... )
>>from operator import itemgetter
map(itemgetter(0), tuple_list)
['John', 'Mark', 'Jeff', 'Bat']

Bye,
bearophile
Jul 11 '08 #2
On Jul 11, 3:36*am, bearophileH...@lycos.com wrote:
James Fassett:
# 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.

The list comprehension is quite more readable to me, so I suggest you
to use it. It's probably the default way to do it in Python.

If you want functional code this is another way (I have not tested the
relative performance but it may be quick):
>tuple_list = (

... * * ('John', 'Doe'),
... * * ('Mark', 'Mason'),
... * * ('Jeff', 'Stevens'),
... * * ('Bat', 'Man')
... * )>>from operator import itemgetter
>map(itemgetter(0), tuple_list)

['John', 'Mark', 'Jeff', 'Bat']

Bye,
bearophile

Functional programmers love pattern matching (which I think makes the
code much easier to understand):

[x for (x,y) in tuple_list]

or

map(lambda (x,y):x, tuple_list)

Jul 11 '08 #3
On Jul 11, 12:00*pm, James Fassett <ja...@reggieband.comwrote:
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])
Here are some various 'functional' solutions. Pick the one that fits
your problem best:

result_list = [fn for fn,ln in tuple_list]

result_generator = (fn for fn,ln in tuple_list)

result_list = map(lambda (fn,ln): fn, result_list)

result_generator = itertools.imap(lambda (fn,ln): fn, result_list)
Jul 11 '08 #4


be************@lycos.com wrote:
James Fassett:
># the first Pythonic attempt using comprehensions
result_list = [x[0] for x in tuple_list]
This has the virtue of working for tuples of any length and doing the
minimal work required.
># the final functional way
[result_list, _] = zip(*tuple_list)
This requires the tuples in tuple_list to be of length 2. It also
produces a second list that is then tossed away.
The list comprehension is quite more readable to me, so I suggest you
to use it. It's probably the default way to do it in Python.
It also has two virtues that the non-equivalent alternative lacks.
If you want functional code this is another way (I have not tested the
relative performance but it may be quick):
>>>tuple_list = (
... ('John', 'Doe'),
... ('Mark', 'Mason'),
... ('Jeff', 'Stevens'),
... ('Bat', 'Man')
... )
>>>from operator import itemgetter
map(itemgetter(0), tuple_list)
['John', 'Mark', 'Jeff', 'Bat']
This again makes just one list from tuples of any length.

Some of the other alternatives in another post do minimal work but only
work with pairs.

tjr

Jul 11 '08 #5
On Jul 12, 12:18*am, George Sakkis <george.sak...@gmail.comwrote:
It relies on positional arguments, tuple unpacking and
the signature of zip(),
It moreso relies on the fact that:
>>t1 = (0,1,2,3)
t2 = (7,6,5,4)
[t1, t2] == zip(*zip(t1, t2))
True

This is mathematically true given the definition of zip. To me that is
very functional. Basically, unpacking a pair list into zip is the
canonical definition of unzipping the list (which is exactly my
intention).
Second, it is less readable,
For a Python programmer - you are correct. For someone familiar with
the use of zip (as described above) - I wonder. Since I am new to this
I can't say for sure. If I posted the same code to a Haskell list or a
ML list would their opinion be the same?
robust and efficient than the list comprehension.
I don't know the internals of how the Python interpreter treats list
comprehensions and zip but it seems reasonable to assume an extra list
is created for the zip approach.

However, in the limited functional code I have seen this is actually a
common practice. I would suppose in languages with lazy evaluation
this isn't a problem - but in Python it would be.
The list comprehension is still the most pythonic approach though.
I agree that it is more Pythonic and preferable in this case.

Cheers,
James
Jul 14 '08 #6
On 14 juil, 11:51, James Fassett <ja...@reggieband.comwrote:
On Jul 12, 12:18 am, George Sakkis <george.sak...@gmail.comwrote:
It relies on positional arguments, tuple unpacking and
the signature of zip(),

It moreso relies on the fact that:
>t1 = (0,1,2,3)
t2 = (7,6,5,4)
[t1, t2] == zip(*zip(t1, t2))

True

This is mathematically true given the definition of zip. To me that is
very functional. Basically, unpacking a pair list into zip is the
canonical definition of unzipping the list (which is exactly my
intention).
Second, it is less readable,

For a Python programmer - you are correct. For someone familiar with
the use of zip (as described above) - I wonder. Since I am new to this
I can't say for sure. If I posted the same code to a Haskell list or a
ML list would their opinion be the same?
You might find interesting than Python's list comprehensions were
stolen from Haskell then !-)
robust and efficient than the list comprehension.

I don't know the internals of how the Python interpreter treats list
comprehensions
According to a post on the pypy team's blog, mostly as sugar candy for
the procedural version (IOW: the generated byte-code will be roughly
equivalent).
and zip but it seems reasonable to assume an extra list
is created for the zip approach.

However, in the limited functional code I have seen this is actually a
common practice. I would suppose in languages with lazy evaluation
this isn't a problem - but in Python it would be.
Python has some kind of lazy evaluation too - look for yield,
generator expressions, iterators, and the itertools package.

Jul 14 '08 #7


James Fassett wrote:
<zip...
>robust and efficient than the list comprehension.

I don't know the internals of how the Python interpreter treats list
comprehensions and zip but it seems reasonable to assume an extra list
is created for the zip approach.
Minor times differences between this and that way of writing things tend
to be version and even system dependent. In 3.0, for instance, zip
produces an iterator, not a list. So it will be faster. On the other
hand, list comprehensions will be a bit slower to fix what many,
including Guido, consider to be a slight design bug.

Jul 14 '08 #8
James Fassett <ja***@reggieband.comwrites:
tuple_list = (
('John', 'Doe'),
('Mark', 'Mason'),
('Jeff', 'Stevens'),
('Bat', 'Man')
)
# the final functional way
[result_list, _] = zip(*tuple_list)
That's really ugly IMO. I'd use:

result_list = list(x for (x,y) in tuple_list)

I don't like square-bracket listcomps because they leak the index
variables to the outside.
Jul 16 '08 #9
Paul Rubin <http://ph****@NOSPAM.invalidwrites:
I don't like square-bracket listcomps because they leak the index
variables to the outside.
According to PEP 289 <URL:http://www.python.org/dev/peps/pep-0289>,
this is an acknowledged wart that will be fixed in Python 3.0.

--
\ “None can love freedom heartily, but good men; the rest love |
`\ not freedom, but license.” —John Milton |
_o__) |
Ben Finney
Jul 16 '08 #10


Ben Finney wrote:
Paul Rubin <http://ph****@NOSPAM.invalidwrites:
>I don't like square-bracket listcomps because they leak the index
variables to the outside.

According to PEP 289 <URL:http://www.python.org/dev/peps/pep-0289>,
this is an acknowledged wart that will be fixed in Python 3.0.
Has been.
IDLE 3.0b1
>>a=[i for i in range(5)]
i
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
i
NameError: name 'i' is not defined

Jul 16 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: beza1e1 | last post by:
I see myself shifting more and more over to the functional kind of coding. Could be related to the Haskell, we had to learn in CS. Now i was wondering, how other people use Python? With...
177
by: C# Learner | last post by:
Why is C syntax so uneasy on the eye? In its day, was it _really_ designed by snobby programmers to scare away potential "n00bs"? If so, and after 50+ years of programming research, why are...
60
by: Shawnk | last post by:
Some Sr. colleges and I have had an on going discussion relative to when and if C# will ever support 'true' multiple inheritance. Relevant to this, I wanted to query the C# community (the...
5
by: shumaker | last post by:
I just read an overview of C# 3.0, and it occured to me that some of these features could make it much easier to write programs that automatically make use of multi core processors. After reading...
15
by: Lorenzo Stella | last post by:
Hi all, I haven't experienced functional programming very much, but now I'm trying to learn Haskell and I've learned that: 1) in functional programming LISTS are fundmental; 2) any "cycle" in FP...
139
by: Joe Mayo | last post by:
I think I become more and more alone... Everybody tells me that C++ is better, because once a project becomes very large, I should be happy that it has been written in C++ and not C. I'm the only...
0
by: happycow2 | last post by:
Hi, I first want to start off by saying that Im not a programmer but rather a 3-D animation/ special effects student, however there are allot of concepts that i come across that are some what...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.