What does Pythonic mean? [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
On many websites I often see comments that code isn't Pythonic, or that there is a more Pythonic way to achieve the same goal.
What does Pythonic mean in this context? For example, why is
while i < someValue:
do_something(list[i])
i += 1
not Pythonic while
for x in list:
doSomething(x)
is Pythonic?

Exploiting the features of the Python language to produce code that is clear, concise and maintainable.
Pythonic means code that doesn't just get the syntax right, but that follows the conventions of the Python community and uses the language in the way it is intended to be used.
This is maybe easiest to explain by negative example, as in the linked article from the other answers. Examples of un-Pythonic code often come from users of other languages, who instead of learning a Python programming patterns such as list comprehensions or generator expressions, attempt to crowbar in patterns more commonly used in C or Java. Loops are particularly common examples of this.
For example, in Java I might use
for (int index = 0; index < items.length; index++) {
items[index].performAction();
}
In Python we can try and replicate this using while loops, but it would be cleaner to use:
for item in items:
item.perform_action()
Or, even a generator expression
(item.some_attribute for item in items)
So essentially when someone says something is un-Pythonic, they are saying that the code could be rewritten in a way that is a better fit for Python's coding style.
Typing import this at the command line gives a summary of Python principles. Less well known is that the source code for import this is decidedly, and by design, un-Pythonic! Take a look at it for an example of what not to do.

Related

What is the most elegant Pythonic way to write an 'if-statement' within a loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
Here is the operation that I want to perform:
for sample in samples:
if sample['something'] is None:
sample['something'] = 'something_else'
I want to write this in a more elegant and Pythonic way. It would be great if some experts in Python could help. samples is a list of dictionaries.
for sample in (elt for elt in samples if elt["something"] is None):
sample["something"] = "something_else"
Note use of generator expression to not build another in-memory list, though this might be unnecessary.
I also would not use explicit None check either, unless empty collections, strings or 0 should be considered "truthy" values -- often they aren't, with the exception of zero. if not foo reads IMO better than if foo is not None. If this is your case too, you could do just
for sample in samples:
sample["something"] = sample["something"] or "something_else"
Then again I wouldn't probably bother, original would be good enough for me, and like suggested in comments, using or shortcut could be a tad hacky (in a bad way) for some readers.

Is there a way to compute the cosets of D<sub>2n</sub> in <i>S</i><sub><i>n</i></sub> [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Although this is a question of maths but I really wanted to figure out if something like this is possible or not by coding it .(preferably in C). I had the question posted in mathsstackexchange where I saw that there's a way to find out the cosets of D_12 in S_6 by using Python programming. Can someone just help me to figure out how are we doing this?
S_n is the group formed by all possible permutations of n-elements and D_2n is formed by the generators <r, s> where r =(123, n) and s=(1n)(2 n-1).
Here's the link to the answer
https://math.stackexchange.com/questions/3880306/find-the-cosets-of-d-2n-in-s-n
Also I am not accustomed to posting questions in stackoverflow, I really don't know how to add mathematical symbols.
Though the logic remains same, the implementation will vary from Python to c due to difference is data types and so on. So you should try learning Python, it’s very easy to learn and you can pick up writing code in Python within few days considering you already you know a few other languages. And writing such complex programs can be easy in Python due to the vast inbuilt libraries and readability. So it’s better if you learn Python and start implementing this in Python.

Is it bad practice to mix OOP and procedural programming in Python (or to mix programming styles in general) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have been working on a program to solve a Rubik's cube, and I found myself unsure of a couple of things. Firstly, if I have a bunch of functions that have general applications (e.g., clearing the screen), and don't know whether or not I should change them to methods inside of a class. Part of my code is OOP and the other part is procedural. Does this violate PEP8/is it a bad practice? And I guess in broader terms, is it a bad idea to mix two styles of programming (OOP, functional, procedural, etc)?
I would say it's not bad at all, if the problem can be solved more easily that way and that your language supports it.
Programming paradigms are just different approaches to solving problems:
Procedural says "What are the steps that need to be performed to solve this problem?"
Functional says "What values should be transformed and how should they be transformed to solve this problem?"
OOP says "What objects need to interact with one another and what messages are needed to be sent between them to solve this problem?"
When you divide up your problem into smaller ones, you might find that some parts of the problem can be solved more easily in a functional way, other parts a procedural way. It's totally possible to have such a problem.
Python is mainly procedural and quite OOP, and has functional features (namely functools). It's not as functional as Haskell and not as OOP as C#, but it allows you to use those paradigms to some extent.

Does code that is equivalent but have different syntax run faster in certain cases? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Does syntax change Big O? Or perhaps change the speed of how a program is processed? I am going to use python as an example.
If I had the list comprehension code:
new_list = [expression(i) for i in old_list if filter(i)]
Would it run any differently than:
new_list = []
for i in old_list:
if filter(i):
new_list.append(expressions(i))
Do these pieces of code have anything different in them? Would one be considered faster than the other? Why or why not?
Big-O says nothing about syntax choice in a programming language. It is only useful as a tool to compare algorithms.
Syntax choices can change the fixed cost of each iteration. Your specific sample has different fixed execution cost per iteration and so the speed of execution will differ.
In Python you could use the timeit module to compare execution speed of two ways to implement the same algorithm, and you could use the dis module to analyse what bytecode will be executed for each alternative 'spelling', informing you how much work the Python interpreter will do for each iteration.
For the specific example, the list comprehension will be faster because it does less work in bytecode; the extra lookups of the .append() method in the second example as well as invoking it is what slows it down.

Optimal Length of a Python Function (Style) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Perhaps this is not the correct place to ask this question, and part of me thinks that there is no real answer to it, but I'm interested to see what experienced Python users have to say on the subject:
For maximum readability, concision, and utility, what is a range for an optimal length of a Python function? (Assuming that this function will be used in combination with other functions to do something useful.)
I recognize that this is incredibly dependent on the task at hand, but as a Sophomore Comp. Sci. major, one of the most consistent instructions from professors is to write programs that are comprised of short functions so as to break them up into "simple", discrete tasks.
I've done a big of digging, including through the Python style guide, but I haven't come up with a good answer. If there are any experienced Python users that would like to weigh in on this subject, I would appreciate the insight. Thanks.
I'm sure a lot of people have strong opinions about this, but for new programmers a good rule of thumb is to try and keep it below 10-20 lines. A better rule of thumb is that a function should do one thing and do that one thing well. If it becomes really long, it is likely doing more than one thing and can be broken down into several functions.

Categories

Resources