{"id":92840,"date":"2021-11-16T19:23:27","date_gmt":"2021-11-16T19:23:27","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=92840"},"modified":"2022-04-27T21:06:55","modified_gmt":"2022-04-27T21:06:55","slug":"10-reasons-python-better-than-c-sharp","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/10-reasons-python-better-than-c-sharp\/","title":{"rendered":"10 reasons why Python is better than C# (or almost any other programming language)"},"content":{"rendered":"<p>Nearly 10 years ago, I wrote <a href=\"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/10-reasons-why-visual-basic-is-better-than-c\/\">an article on this website<\/a> comparing C# unfavourably with Visual Basic, which prompted many comments, roughly equally divided between praise and censure. My favourite two (now sadly removed) were \u201cYour website looks like Teletubbieland\u201d (which had some truth at the time, but wasn\u2019t strictly relevant) and \u201cYou know f*** all about C#\u201d, which had relevance but \u2013 I believe \u2013 less truth (and in its original form didn\u2019t have any asterisks either!).\u00a0To celebrate this anniversary, I\u2019ve decided to reawaken all of you slumbering C# trolls with 10 reasons why Python is better than C# (and better than most other programming languages, too, it has to be said).<\/p>\n<h2>1 \u2013 Indented code blocks<\/h2>\n<p>These are just beautiful! Here\u2019s how you can write a loop and condition in Python to play <a href=\"https:\/\/en.wikipedia.org\/wiki\/Fizz_buzz#:~:text=Players%20generally%20sit%20in%20a,by%2015%20become%20fizz%20buzz.\">Fizz-Buzz<\/a> in Python:<\/p>\n<pre class=\"lang:c# theme:vs2012\">for integer in range(1,11):\r\n\u00a0 \u00a0 # for first 10 numbers\r\n\u00a0 \u00a0 if integer % 3 == 0:\r\n\u00a0 \u00a0 \u00a0 \u00a0 print(integer, \"Fizz\")\r\n\u00a0 \u00a0 elif integer % 5 == 0:\r\n\u00a0 \u00a0 \u00a0 \u00a0 print(integer,\"Buzz\")<\/pre>\n<p>Notice anything? There are no silly { } brackets to denote when a condition or loop block starts and ends because Python can infer this from the indentation. Why type characters when you don\u2019t have to?<\/p>\n<h2>2 \u2013 Self-declaring Variables<\/h2>\n<p>Here\u2019s how you can declare variables in four programming languages:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-92841\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/11\/table-description-automatically-generated.png\" alt=\"An image showing how to declare variables in several languages\" width=\"382\" height=\"271\" \/><\/p>\n<p>In Python, you don\u2019t \u2013 and can\u2019t \u2013 declare variables. Instead, you just assign values to them:<\/p>\n<pre class=\"lang:c# theme:vs2012\"># create a variable to hold the meaning of life\r\nmeaning_of_life = 42<\/pre>\n<p>Python then creates a variable of the appropriate type (you can prove this by printing out its value):<\/p>\n<pre class=\"lang:c# theme:vs2012\"># show the type of this, and its value\r\nprint(type(meaning_of_life),meaning_of_life)<\/pre>\n<p>This code would show <strong>&lt;class &#8216;int&#8217;&gt; 42. <\/strong>Another nice thing about Python variables is how simple the data types are: there are only integers, floating point numbers, strings, and Boolean values, which is pretty much all a programming language needs, dates being just formatted numbers when all\u2019s said and done).<\/p>\n<p>Now C# programmers will \u2013 like I did \u2013 initially throw their arms up in horror at this, but haven\u2019t we all been writing lines of code like this for years?<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/ store life's meaning\r\nvar meaningOfLife = 42;<\/pre>\n<p>This statement does exactly the same thing: it sets the type of the variable from the context.<\/p>\n<p>I\u2019ve found not having to declare the type of variables strangely liberating, to the extent that I now resent having to declare variables when I go back to writing code in C# or SQL.<\/p>\n<h2>3 \u2013 Those modules \u2026<\/h2>\n<p>Python is Python because of its modules: literally thousands of add-ins, covering everything from scraping websites to advanced AI tasks.<\/p>\n<p>But wait a bit, you may say \u2013 C# (at least as it\u2019s written in .NET, which is surely the most common implementation) has \u201cmodules\u201d too. Here are just a few of the ones in the <strong>System<\/strong> namespace:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-92842\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/11\/graphical-user-interface-application-table-desc.png\" alt=\"An image showing a Using statement in C# and all the options\" width=\"327\" height=\"285\" \/><\/p>\n<p>The answer to which is: yes, it does, but \u2026 Python modules are so much easier to use. To illustrate this, let\u2019s take an example: looping over the subfolders in a folder. Here\u2019s how you could do this in Python:<\/p>\n<pre class=\"lang:c# theme:vs2012\">import os\r\n# get a list of all the files in a folder\r\nfiles = os.listdir(r\"C:\\__work\\\\\")\r\n# loop over these files\r\nfor file in files:\r\n\u00a0 \u00a0 # show its name\r\n\u00a0 \u00a0 print(file)<\/pre>\n<p>Here\u2019s the approximate equivalent C# code:<\/p>\n<pre class=\"lang:c# theme:vs2012\">using System.IO;\r\nvar folder = new DirectoryInfo(@\"C:\\__work\\\");\r\nforeach (DirectoryInfo dir in folder.GetDirectories())\r\n{\r\nDebug.WriteLine(dir.Name);\r\n}<\/pre>\n<p>I\u2019m aware that it\u2019s subjective, but I find the Python modules to be almost without exception more logically constructed and easier to learn than the equivalent .NET ones, for example.<\/p>\n<h2>4 \u2013 Simplicity of Data Structures<\/h2>\n<p>C# has (deep breath now) the following data structures: <code>Array<\/code>, <code>ArrayList<\/code>, <code>Collection<\/code>, <code>List<\/code>, <code>Hashtable<\/code>, <code>Dictionary<\/code>, <code>SortedDictionary<\/code>, <code>SortedList<\/code>. These implement the <code>IEnumerable<\/code> or <code>IDictionary<\/code> interfaces. If you\u2019re thinking of learning C#, I\u2019ve probably just put you off for life!<\/p>\n<p>Python has four structures: lists, tuples, dictionaries, and sets, although the first two are virtually identical from the programming point of view. Purists will say that you need all the different data types that C# provides, but trust me, you don\u2019t.<\/p>\n<p>It\u2019s not just that Python only has a few data structures; the ones it does have are so easy to use. Here\u2019s how you create a sorted list of fruit, for example:<\/p>\n<pre class=\"lang:c# theme:vs2012\"># create an empty list\r\nfruit = []\r\n# add some fruit\r\nfruit.append(\"Pears\")\r\nfruit.append(\"Apples\")\r\nfruit.append(\"Bananas\")\r\n# sort this\r\nfruit.sort()\r\n# print\r\nprint(fruit)\r\n<\/pre>\n<p>Programming doesn\u2019t get any more straightforward than this!<\/p>\n<h2>5 \u2013 Slicing<\/h2>\n<p>I\u2019m not generally a fan of languages that try to cram as much logic into as few characters as possible (that\u2019s why I don\u2019t like regular expressions and didn\u2019t get on with Perl).<\/p>\n<p>However, slicing sequences has the big advantage that it\u2019s used everywhere in Python, so once you\u2019ve learnt a few simple rules, you can pick out anything you want. And there\u2019s a certain beauty in code like this:<\/p>\n<pre class=\"lang:c# theme:vs2012\"># the seven deadly sins\r\nsins = [\"pride\", \"envy\", \"gluttony\", \"greed\", \"lust\", \"sloth\", \"wrath\"]\r\n# every other one, but missing the first and last\r\n# ie ['envy', 'greed', 'sloth']\r\nselected_sins = sins[1:-1:2]\r\nprint(selected_sins)<\/pre>\n<p>The great thing about slicing is that it carries through to everything. Once you\u2019ve learnt how to slice a tuple, for example, you\u2019ve also learnt how to slice a multi-dimensional array (in numpy) or an Excel-style dataframe (in pandas) or any other sequence of items.<\/p>\n<h2>6 \u2013 For loops<\/h2>\n<p>C# has two separate loop structures, depending on whether you\u2019re looping over numbers or objects, as shown by these two examples:<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/ first 5 numbers\r\nfor (int i=0; i &lt;= 5; i++) {\r\nDebug.Print(i.ToString());\r\n}\r\n\/\/ words in a string\r\nstring[] words = {\"Simple\",\"Talk\"};\r\nforeach (string word in words)\r\n{\r\nDebug.Print(word);\r\n}<\/pre>\n<p>Here is the same code in Python:<\/p>\n<pre class=\"lang:c# theme:vs2012\"># first 5 numbers\r\nfor i in range(1,6):\r\n\u00a0 \u00a0 print(i)\r\n# words in a string\r\nwords = {\"Simple\",\"Talk\"}\r\nfor word in words:\r\n\u00a0 \u00a0 print(word)<\/pre>\n<p>Notice that not only is the Python for loop syntax simple and easier to understand, but there\u2019s only one version of it (unlike in C#, where sometimes you use <code>for<\/code> and sometimes <code>foreach<\/code>).<\/p>\n<h2>7 &#8211; List comprehensions<\/h2>\n<p>A list comprehension is one of the most beautiful programming constructs I\u2019ve seen. You can use it as a substitute for C# lambda or anonymous functions, and the result is transparent.<\/p>\n<p>Here\u2019s an example listing out the cubes of all the even numbers up to 10:<\/p>\n<pre class=\"lang:c# theme:vs2012\"># cubes of even numbers up to and including 10\r\n# (would give [8, 64, 216, 512, 1000] as output)\r\nprint([n ** 3 for n in range(1,11) if n % 2 == 0])<\/pre>\n<p>You could of course do this the long way round:<\/p>\n<pre class=\"lang:c# theme:vs2012\">for n in range(1,11):\r\n\u00a0 \u00a0 if n % 2 == 0:\r\n\u00a0 \u00a0 \u00a0 \u00a0 print(n ** 3)<\/pre>\n<p>It\u2019s hard to think how you could improve the syntax of the first method: show me <em>this<\/em> for <em>these<\/em> numbers where <em>this condition<\/em> is true.<\/p>\n<h2>8 \u2013 Sets<\/h2>\n<p>I said just now that list comprehensions are beautiful, but so too are sets.<\/p>\n<p>For example, the way to remove duplicates from a list of items in Python is just to convert the list to a set (since sets can\u2019t contain duplicate items, any duplicates will be removed), then convert the set back to a list. Like this, say:<\/p>\n<pre class=\"lang:c# theme:vs2012\"># this contains some duplicates\r\nlanguages = [\"C#\",\"Python\",\"VB\",\"Java\",\"C#\",\"Java\",\"C#\"]\r\n# this set can't\r\nlanguage_set = set(languages)\r\n# convert back to a list\r\nlanguages = list(language_set)\r\n# this will give: ['C#', 'Java', 'Python', 'VB']\r\nprint(languages)<\/pre>\n<p>However, sets don\u2019t just provide an elegant way to remove duplicates from lists; they also allow you to find the intersection or union of two groups of items (those long-ago maths lessons learning Venn diagrams weren\u2019t wasted after all!).<\/p>\n<p>Pretty much everything you need to know about sets in Python is covered by these few lines of code:<\/p>\n<pre class=\"lang:c# theme:vs2012\"># create two sets: Friends characters and large Antarctic ice shelves\r\nfriends = {\"Rachel\",\"Phoebe\",\"Chandler\", \"Joey\",\"Monica\",\"Ross\"}\r\nice_shelves = {\"Ronnie-Filchner\", \"Ross\", \"McMurdo\"}\r\n# show the intersection (elements in both lists)\r\nprint(friends &amp; ice_shelves)\r\n# show the union (elements in either list)\r\nprint(friends | ice_shelves)\r\n# show the friends who aren't ice shelves\r\nprint(friends - ice_shelves)\r\n# elements in either set but not both\r\nprint(friends ^ ice_shelves)<\/pre>\n<p>This code would give this output ( \u201cRoss\u201d is the only item in both lists, for example):<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-92843\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/11\/a-picture-containing-scatter-chart-description-au.png\" alt=\"An images showing the output of sets in Python\" width=\"888\" height=\"113\" \/><\/p>\n<h2>9 &#8211; Working with files and folders<\/h2>\n<p>Virtually everything to do with files and folders is easier than you think it\u2019s going to be. Want to write out the contents of a list? No need to import modules &#8211; just do this :<\/p>\n<pre class=\"lang:c# theme:vs2012 \"># list of 3 people\r\npeople = [\"Shadrach\",\"Meshach\",\"Abednego\"]\r\n# write them to a file\r\nwith open(r\"c:\\\\wiseowl\\people.txt\",\"w\") as people_file:\r\n\u00a0 \u00a0 people_file.writelines(\"\\n\".join(people))<\/pre>\n<p>Want to export this as a CSV file? Just use the built-in csv module:<\/p>\n<pre class=\"lang:c# theme:vs2012\">import csv\r\n# write student amesto a file\r\nwith open(r\"c:\\\\wiseowl\\students.csv\",\"w\",newline=\"\") as people_file:\r\n\u00a0 \u00a0 potter_file = csv.writer(people_file)\r\n\u00a0 \u00a0 # use this to write out 3 rows\r\n\u00a0 \u00a0 potter_file.writerow([\"Harry\", \"Gryffindor\"])\r\n\u00a0 \u00a0 potter_file.writerow([\"Draco\", \"Slytherin\"])\r\n\u00a0 \u00a0 potter_file.writerow([\"Hermione\", \"Gryffindor\"])<\/pre>\n<p>I could go on to show reading from or writing to JSON files, Excel files, any files using pandas \u2026 Python modules make coding as easy as it can be!<\/p>\n<h2>10 \u2013 The quality of online help<\/h2>\n<p>Here are the results of a search using a well-known search engine (!) for the phrase <strong>C# tutorial<\/strong>:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-92844\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/11\/graphical-user-interface-text-application-descr.png\" alt=\"An images showing the number of results when searching on C# tutorial\" width=\"383\" height=\"201\" \/><\/p>\n<p>Here are the results for the same search using the phrase <strong>Python tutorial<\/strong>:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-92845\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/11\/graphical-user-interface-text-application-descr-1.png\" alt=\"An image showing the results of searching on Python tutorial\" width=\"389\" height=\"201\" \/><\/p>\n<p>But it\u2019s not just that Python has nearly four times as many tutorial page results: the tutorials themselves are much better, IMHO.<\/p>\n<h2>Two reasons not to like Python<\/h2>\n<p>It would be disingenuous to end this article without giving two areas in which Python doesn\u2019t compare well with other languages like C#.<\/p>\n<p>The first way in which Python underperforms is that it\u2019s so hard to get started. In C#, you\u2019re probably going to choose Visual Studio as your development environment, and while you will have teething problems, at least everything is integrated. In Python, you have to choose whether to use Visual Studio Code, PyCharm, Jupyter Notebook, or any of a dozen other candidates for your IDE (Integrated Development Environment). Even when you\u2019ve chosen your IDE, you\u2019ll still have to learn how to set up \u201cvirtual environments\u201d in which you can install modules for different applications that you\u2019re creating so that they don\u2019t interfere with each other. None of this is straightforward, and it\u2019s a serious impediment to getting started with Python.<\/p>\n<p>The second way in which Python underperforms is that it isn\u2019t always strongly typed. This limitation is best illustrated by an example. Consider this segment of Python code:<\/p>\n<pre class=\"lang:c# theme:vs2012\">def add_numbers(first:int,second:int) -&gt; int:\r\n\u00a0 \u00a0 # add the two numbers together\r\n\u00a0 \u00a0 return first + second\r\n# test this out\r\nprint(add_numbers(3,5))\r\n# now test this with some text\r\nprint(add_numbers(\"Simple\",\"Talk\"))<\/pre>\n<p>It creates a function to add two numbers together, then calls it twice. The first call will give 8 (the sum of 3 and 5), while the second will give \u201cSimpleTalk\u201d (treating the \u201c+\u201d in the function as a concatenation symbol).<\/p>\n<p>The problem is this line:<\/p>\n<pre class=\"lang:c# theme:vs2012\">def add_numbers(first:int,second:int) -&gt; int:<\/pre>\n<p>This is sometimes referred to as <em>duck typing<\/em>: if it looks like a duck and quacks like a duck, it\u2019s probably a duck. Except that this looks like an integer and is passed as an integer \u2013 and yet is happily accepting a string into the function. The data types are just hints, it turns out: a serious limitation.<\/p>\n<h2>Interpreted not compiled<\/h2>\n<p>One other big difference between Python and other languages is that the former is interpreted rather than compiled. What this means is that when you run a Python program, the instructions are read as text in sequential order (no executable file is constructed first from the human-readable statements translated into machine-readable language). However, I still can\u2019t decide if this is a good or bad thing, so I have left it off both lists above!<\/p>\n<h2>Why Python is better than C#<\/h2>\n<p>Python was created by Dutch programmer Guido van Rossum to be as easy to use as possible; he succeeded in his aim! Although the Monty Python references in documentation get a bit tedious (even for this diehard fan), if you\u2019re an experienced C# programmer, you will enjoy the simplicity of programming in Python.<\/p>\n<p>&nbsp;<\/p>\n<p><em>If you like this article, you might also like\u00a0<\/em><a href=\"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/10-reasons-why-visual-basic-is-better-than-c\/\"><em>10 Reasons Why Visual Basic is Better Than C#<\/em> <\/a><\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>After resisting learning Python for years, assuming it was just another object-oriented programming language, Andy Brown now gets what the fuss was about: Python really does make coding quicker. This article lists 10 reasons why Python is better than C# and will make your programming life easier (and two reasons, in fairness, why it might not).&hellip;<\/p>\n","protected":false},"author":9783,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143538,53,146042],"tags":[5134],"coauthors":[6782],"class_list":["post-92840","post","type-post","status-publish","format-standard","hentry","category-dotnet-development","category-featured","category-python","tag-sql-prompt"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/92840","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/9783"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=92840"}],"version-history":[{"count":9,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/92840\/revisions"}],"predecessor-version":[{"id":92855,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/92840\/revisions\/92855"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=92840"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=92840"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=92840"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=92840"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}