Keywords in Python and C
How to start comparing two programming languages? Begin at the core by analyzing the keywords (a small set of words that are important to the language, and reserved) that are exclusive to both languages.
UPDATE Mar 2024: Added lambda
to the unique keyword list in Python.
Comparing Python and C through Keywords
As reported elsewhere (http://j.mp/reservedWords), here are some popular languages and the count of keywords in each of them.
For quite some time, with only 31 keywords, Python (Version 2) had held the distinction of being the “language with the least number of keywords”. Of course, we need to ignore Smalltalk (6) and the not-yet-mainstream Go (25) and Elm (25).
But with the transition to Python 3, that distinction has been ceded back to the good old C language (total keywords is 32). In any case, I was quite curious as to what were the additional keywords that were added to the language. Here’s what I came up with:
- In the transition from Python_2 to Python_3, there have been six changes to the keyword list — four were added and two were removed, resulting in a net addition of two.
- UPDATE (May 2023): Python 3.9.5 now has 36. Launch this!
Net Change is +6–4 = +2
Keywords added to Python_3: {'None', 'nonlocal', 'True', 'False'}
Keywords removed from: {'print', 'exec'}
Total changes: 6
Note: Both print
and exec
have been removed as keywords but retained as built-in functions. For an in-depth and insightful answer on behaviour of exec
in Python 3 vis-à-vis Python 2, read this.
“Core” Python versus “Core” C
If you really think about it, it is not an apples-to-apples comparison when you compare the count of keywords in a strictly typed language (C, Java, etc.) versus a dynamic language (Python). Also, C does not have syntax that supports object-oriented programming or exception handling, whereas Python does.
Nevertheless, for the benefit of a developer/student who is familiar with core Python and is keen on familiarizing with the core part of the C language, the journey can start with a critical inspection of the keywords in both the languages. While “type-less” C has 21 keywords, “essential” Python (sans keywords related to objected orientation and exception handling) has 16 keywords.
-----------------------
Comparing keywords in Python and type-less C
-----------------------
Python: ['break', 'class', 'continue', 'def', 'del',
'else', 'for', 'global', 'if', 'in', 'is',
'nonlocal', 'pass', 'return', 'while']
# Total - 15 "type-less" C Language: ['auto', 'break', 'const',
'continue', 'do', 'else', 'enum', 'extern', 'for',
'goto', 'if', 'lambda', 'register', 'return', 'sizeof',
'static', 'struct', 'typedef', 'union', 'void',
'volatile', 'while']
# Total - 21
If you remove the keywords that are common to both the above lists, here’s what remains:
------ DIFFERENCE -------
extra in python: ['class', 'def', 'del',
'global', 'in', 'is', 'lambda', 'nonlocal', 'pass'] 9extra in clang: ['auto', 'const', 'do', 'enum',
'extern', 'goto', 'register', 'sizeof', 'static',
'struct', 'typedef', 'union', 'volatile'] 14
My analysis below will attempt to compare and contrast the two languages by referring to the above 22 keywords (8 that exists only in Python
verus 14 that exists only in C language
).
Part 0 (programming constructs)
- The
do-while
loop construct exists in C, but not in Python.
enum
exist in C to give variable-like labels to numeric values. You can also define constant values (and macros) using preprocessor directives (#define). There is no support for something like this in Python.- C has the keywords
switch-case-default
that help implement the multi-conditional constructs which can be quite elegant when used withenum.
The equivalent of this can be codified with a series of non-elegantif-elif
statements or using the more elegantdict
datatype in Python. goto
allows you to jump to an arbitrary location in theC
code, and allowing for obscure source code to be written. And for that reason, it is recommended that this keyword be used sparingly. But then, see below for a code snippet from the Linux kernel code that usesgoto
. Go figure. There is no support for this kind of conditional jumps in Python.
- A function or class definition in Python requires
def
which is not required in C.lambda
is a keyword used to create anonymous functions in Python. pass
- a Python statement which has no effect; the equivalent of this is best achieved in C by using the;
delimiter.
Part 1 (scope)
- Scope options are accomplished by using
global
andnonlocal
in Python, whereas in C the keywordsauto
,static
andextern
are used. - C continues to be one of the few languages that allows you to get close to the metal, and that is why it has keywords like
register
andvolatile
. - For example, keyword
volatile
is used to declare volatile variables, which are variables that can be changed by external factors, such as hardware devices. - The keyword
register
is used to declare register variables, which are variables that are stored in CPU registers instead of memory. “A CPU register can be accessed in less than a CPU cycle on modern super-scalar CPUs (as opposed to going to memory which can take 100–300 CPU cycles.”
Part 2 (objects and immutability)
- Python supports object-oriented programming with the
class
keyword whereas the closest equivalents in C would bestruct
andtypedef
. The memory-efficient constructunion
, is unique to C and is not found in other strictly typed languages. - In Python, where everything is an object, there is an explicit
del
keyword. - At compile time, the C programmer can signal the need for immutability by using
const
as a prefix along with the data type. In Python, the mutability or immutability of an object is determined by its type.
Part 3 (object inspection)
- Member introspection in a sequence or collection is possible in Python using the
in
keyword - there is no equivalent of that in C. - Object equivalence is supported in Python and the keyword
is
is used to accomplish this. It returnsFalse
even if the objects are 100% equal.
Part 4 (related to memory)
sizeof
- is it a macro or a keyword? that’s a source for intense debate. The keyword is typically used when invoking dynamic memory allocation. In contrast, explicit memory management is non-existent in Python.- A comparison of the operators supported in the languages highlights a significant difference: C language heavily utilizes pointers. Using the unary
& and *
(address and de-referencing) operators, pointer variables in C allows the programmer to “write to the metal”, i.e. have direct access to and modification of memory.
Misc
Remember, the above analysis has been about comparing “type-less” C and “non-OOP and exception handling free” Python. Again, an important capability of the C language is its support for preprocessor directives (using #define and #undef) for defining macros.
For contrast, also see the typical (and rather boring!) analysis of these two languages at https://medium.com/edureka/python-vs-c-b83446bc2c23 .
Pop Quiz
What does Python dynamically provide for that the C language doesn’t? What does the C language dynamically provide for that Python doesn’t?
Program listing
The above lists of keywords were generated using a Python (Version 3) program which is listed below.
import keyword
python3 = keyword.kwlist# this can be obtained from a Python2 interpreter
# by using the above two statements
#
python2 = [
'and', 'as', 'assert', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'exec',
'finally', 'for', 'from', 'global', 'if', 'import',
'in', 'is', 'lambda', 'not', 'or', 'pass', 'print',
'raise', 'return', 'try', 'while', 'with', 'yield'
]# new keywords in Python 3
additional = set(python3) - set(python2)
print("Keywords added to Python3:", additional)removed = set(python2) - set(python3)
print("Keywords removed from:", removed)print("Total changes:", len(additional) + len(removed))
print("-----------------------")
print("Comparing keywords in Python and C")
print("-----------------------")'''
# get keywords for C from webpages
# write a scrap program by processing links in
https://www.programiz.com/c-programming/list-all-keywords-c-language
http://tigcc.ticalc.org/doc/keywords.html#switch
'''
clang = []
with open("programiz.txt", "r") as fp:
links = fp.readlines()
for link in links:
try:
link.index("list-all-keywords-c-language#")
hashsymbol = link.find("#")
keyword = link[hashsymbol+1:-1]
#print("found keyword", keyword)
list = keyword.split("_") clang.extend(klist)
except:
passclang.extend(["size_t", "NULL"])clangRemove = [
'NULL',
'char', 'int', 'float', 'double', 'long', 'size_t', 'void',
'short', 'unsigned', 'signed',
'switch', 'case', 'default',
# 'auto', 'volatile', 'register',
# 'enum', 'typedef',
]clang = [
keyword for keyword in clang
if keyword not in clangRemove
]pythonRemove = [
'None', 'False', 'True',
'assert', 'with', 'yield', 'lambda',
'try', 'except', 'finally', 'raise',
'import', 'from', 'as',
'and', 'or', 'not',
'elif'
]python3 = [
keyword for keyword in python3
if keyword not in pythonRemove
]print("Python:", sorted(python3), len(python3))
print()
print("'typefree' C Language:", sorted(clang), len(clang))
print("\n------ DIFFERENCE -------")
pextra = set(python3) - set(clang)
cextra = set(clang) - set(python3)
print("extra in python:", sorted(pextra), len(pextra))
print("extra in clang:", sorted(cextra), len(cextra))
Program Output
Keywords added to Python3: {'None', 'nonlocal',
'True', 'False'}
Keywords removed from: {'print', 'exec'}
Total changes: 6
-----------------------
Comparing keywords in Python and C
-----------------------
Python: ['break', 'class', 'continue', 'def', 'del',
'else', 'for', 'global', 'if', 'in', 'is',
'nonlocal', 'pass', 'return', 'while'] 15'typefree' C Language: ['auto', 'break', 'const',
'continue', 'do', 'else', 'enum', 'extern', 'for',
'goto', 'if', 'register', 'return', 'sizeof',
'static', 'struct', 'typedef', 'union', 'void',
'volatile', 'while'] 21------ DIFFERENCE -------
extra in python: ['class', 'def', 'del', 'global',
'in', 'is', 'nonlocal', 'pass'] 8
extra in clang: ['auto', 'const', 'do', 'enum',
'extern', 'goto', 'register', 'sizeof', 'static',
'struct', 'typedef', 'union', 'volatile'] 14
Useful links
- Google’s AI search output — https://bit.ly/3v1Jecn
- Python and C — Comparisons and Contrast shttps://www.rose-hulman.edu/class/cs/csse120/Resources/C/Python_vs_C.html
- Learn XinY minutes https://learnxinyminutes.com/docs/c/
- C for Python Programmers https://web.archive.org/web/20190315070958/http://www.toves.org/books/cpy/
- Short tutorial http://techbeamers.com/python-keywords-identifiers-variables/
- Tutorial for each of the Python keywords: http://j.mp/python3Keywords
- See another comparison https://kov.ai/cppJS or http://bit.ly/keywordsJSVsCpp (between C++ and JavaScript) written by a former KiTE student