Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (20.3k points)

I have seen in many websites that the code isn't pythonic. Is there a much more pythonic way to get to the same goal in this case?

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?

2 Answers

0 votes
by (40.7k points)

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 examples, as in the linked article from the other answers. Examples of unpythonic 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 i in (i; i < items.length ; i++)

 {

  n = items[i];

 ... now do something

 }

In Python, we can try and replicate this using while loops but it would be cleaner to use

for i in items:

  i.perform_action()

Or, even a generator expression

(i.some_attribute for i in items)

So essentially when someone says something is unpythonic, they are saying that the code could be re-written in a way that is a better fit for pythons 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, unpythonic! Take a look at it for an example of what not to do.

0 votes
by (108k points)

Please be informed that the term 'Pythonic' means the code that is written in Python. Like if you write the code in C++ to interchange the values of the variable, this is how you will do in C++:

int temp 

temp = a; 

a = b; 

b = temp; 

The Pythonic way is:

a, b = b, a 

Related questions

0 votes
1 answer
0 votes
4 answers
0 votes
1 answer
asked Dec 30, 2020 in Python by ashely (50.2k points)
0 votes
1 answer

Browse Categories

...