
Table of Contents
Python is a general-purpose programming language. You can understand its growth in the last couple of years by considering its approachability for learning and its high suitability for data analysis, machine learning, and web development. But what kind of programming language is it? What are some differences when you compare Java vs Python? What can you do with it? And is it really as “easy to learn” as some people claim?
You’ll explore Python from a Java perspective in this tutorial. After you’ve read it, you’ll be able to decide whether Python is a viable option to solve your use cases and to appreciate when you can use Python in combination with Java for certain types of problems.
In this tutorial, you’ll learn about:
This tutorial is for software developers who are familiar with Java’s inner workings, concepts, terminology, classes, types, collections framework, and so on.
You don’t need to have any Python experience at all.
Free Bonus:Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.
Python is a programming language that was developed byGuido van Rossum. He was looking for a hobby programming project that would keep him occupied during the Christmas holiday in 1989, so that’s when he started developing the Python interpreter.
Python has its origins in a number of languages:ABC,C, andModula-3. It’s basically an object-oriented, imperative programming language.
Depending on your preference and desired functionality, it can be applied in a full object-oriented style or in a procedural programming style with functions. The object-oriented capabilities are addressedlater in this tutorial.
Note: Just for clarity, from a Java perspective, Pythonfunctions are likestatic methods, and you don’t necessarily need to define them within a class.Later on, you’ll see an example of a Python function definition.
Additionally, a more functional programming style is also perfectly possible. To learn more, you’ll want to explorePython’s functional programming capabilities.
In early 2021, TIOBE announced Python as theprogramming language of the year for the fourth time. As of the 2021Octoverse report, Python ranks as the second most popular language on GitHub by repository contributors.
Soon, you’ll get hands-on with Python in thesections following this one. First, however, you’ll explore why it’s worth getting to know Python better by going through some features that you can trace back to Python’s philosophy.
Some ideas behind Java and Python are similar, but every programming language has its own unique characteristics. The philosophy of Python is captured as a collection of nineteen guiding principles, theZen of Python. Python hides a few Easter eggs, and one of them is the Zen of Python. Consider what happens when you issue the following command in the Pythonread–eval–print loop (REPL):
>>>importthisThe Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren't special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one-- and preferably only one --obvious way to do it.Although that way may not be obvious at first unless you're Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it's a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea -- let's do more of those!While you shouldn’t take the statements above too literally, a few of these relate directly to the characteristics that you’ll walk through next.
Note: The Python read–eval–print loop is explained later on in this tutorial.
By considering the guiding principles of the Zen of Python, you’ll get a good idea about how you can approach working with the language.
If you come from a Java background and you look at a typical fragment of Python code, you might think that you’re looking at pseudo-code. There are a few factors that contribute to this:
You can find a few examples of how this appears in practice during this tutorial, as well as in other linked resources.
The aim of Python is that you can solve the majority of everyday problems with just the standard distribution of Python. To that purpose, Python includes what’s called thestandard library. Just like theJava Class Library, it’s an extensive collection of useful facilities consisting of constants, functions, classes, and frameworks.
For further acquaintance with the Python standard library, check out thefirst part and thesecond part of the Brief Tour of the Standard Library in the Python docs’Python tutorial.
Python provides several features that enable you to develop code that you can reuse in different places to apply theDon’t Repeat Yourself (DRY) principle.
One feature is that you typically decompose your code intomodules andpackages within Python. Note, however, that Python modules and packages are different from Java modules and packages. If you want to learn more about these concepts from the perspective of a Python developer, you can read aboutPython modules and packages.
Another technique that you can use within Python is object-oriented programming. You’ll explore thislater on in this tutorial.
You can also usedecorators to modify Python functions, classes, or methods. This is yet another technique so that you can program functionality only once, after which it can be used from any function, class, or method that you’ve decorated.
The support of modules and packages is one of the ingredients that makes it easy to extend Python with new functionality. You can also define new or adapted behavior to Python standard operators and functions byoverloading them. It’s even possible to influence howclasses are created.
The most straightforward way to extend Python is to write your code in pure Python. You can also define modules byusing bindings in a stripped-down dialect of Python, called Cython, or in C or C++.
In this tutorial, you’ll find examples that might encourage you to explore certain things or to try out Python code fragments for yourself. As a Java developer, you might remember your first steps in getting acquainted with Java and installing your first Java Development Kit. Likewise, if you want to get started with Python, you’ll first need to install it and then create a sandbox where you can safely experiment.
There are already a couple of tutorials that explain how to do this, so the next subsections will point you to these resources.
The first step is to install a recent version of Python. In order to do that, follow thisPython installation and setup guide.
Another place you can look for installation instructions is theofficial Python download page.
Note: Make sure you’ve installed a recent version of Python. At the time of writing this tutorial, the most recent version is the latest patch version of the3.10.x series. The code fragments shown in this tutorial should all work with this version of Python.
Many Python developers contribute to libraries that support various Python versions, and they often prefer to try out a pre-release of Python without disturbing their regular Python work. In those situations, it’s convenient to have access to multiple versions of Python on the same machine. A tool that provides that functionality ispyenv, which is comparable to Java’sjEnv.
As a second step, you should set up a virtual environment so that you can safely take advantage of the open source Python ecosystem. This section explains how and why you should do that.
Although Python comes with an extensivestandard library with all kinds of functionality, there’s even more functionality available in the form ofexternal packages, of which the vast majority are open source. ThePython Package Index, orPyPI for short, is the main central repository that collects and provides these packages. You can install packages with thepip command. Before you do that, however, first read the next two paragraphs.
To avoid dependency version conflicts, you generally shouldn’t share your global or personal Python installation between projects. In practice, you accompany each project or experimentation sandbox with avirtual environment.
This way, your projects stay independent from one another. This approach also prevents version conflicts between packages. If you want to know more about this process, then you can read in detail about how tocreate and activate your virtual environments.
As a final step to getting set up, decide on which editor or IDE you’d like to use. If you’re used to IntelliJ, thenPyCharm seems to be the logical choice because it belongs to the same line of products. Another popular editor on the rise isVisual Studio Code, but you can also choose frommany other options.
After you’ve installed Python, learned how to install external packages into a virtual environment, and chosen an editor or IDE, you can start experimenting with the language. As you read through the rest of this tutorial, you’ll find plenty of opportunities to experiment and practice.
You can quickly get a feel for what kind of programming language Python is by looking at where the most striking differences are. In the following subsections, you’ll get to know the most important ways that Python is different from Java.
Perhaps the most striking feature of Python is its syntax. In particular, the way you specify its functions, classes, flow-control constructs, and code blocks is quite different from what you might be used to. In Java, you indicate code blocks with the well-known curly braces ({ and}). In Python, however, you indicate code blocks by theindent level. Here you see an example that demonstrates how the indentation determines code block grouping:
1defparity(number): 2result="odd"# Function body 3ifnumber%2==0: 4result="even"# Body of if-block 5returnresult# Not part of if-block 6 7fornuminrange(4):# Not part of function 8print("Number",num,"is",parity(num))# Body of for-loop 9print("This is not part of the loop")# Not part of for-loopThe code displays a few new concepts:
def statement starts the definition of a newfunction namedparity(), which accepts an argument callednumber. Note that if thedef statement had appeared within a class definition block, it would have started amethod definition instead.parity(), the function body starts on anindented level. The first statement is an assignment of the"odd" string to theresult variable.if statement.if statement,number % 2 == 0, evaluates to true. In the example, it only consists of a single line where you assign"even" to theresult variable.return statement marks the end of theif statement and its associated block.for loop. Consequently, thefor loop starts at the same indent level as the start of the function definition block back on the first line. It marks the end of the function definition block.for loop. The firstprint() function call is part of thefor loop block.print() function call isn’t part of thefor loop block.You might have noticed that a colon (:) at the end of a line introduces a new sub-block of code, which should be indented one level. This code block ends when the next statement is dedented again.
A code block must consist of at least one statement. An empty code block is simply not possible. In the rare occasion that there isn’t any statement needed, you can use thepass statement, which does nothing at all.
Finally, you’ve probably also noticed that you can use the hash sign (#) for comments.
The above example will result in the following output:
Number 0 is evenNumber 1 is oddNumber 2 is evenNumber 3 is oddThis is not part of the loopAlthough this way of defining blocks may seem weird at first sight and might even scare you off, experience shows that people get used to it sooner than you might be thinking right now.
There’s a helpfulstyle guide for Python code calledPEP 8. It recommends using an indent level of four positions, using spaces. The style guide doesn’t recommend using tabs in the source code files. The reason is that different editors and system terminals might use inconsistent tab stop positions and render the code differently for various users or between various operating systems.
Note: The style guide is an example of aPython Enhancement Proposal, orPEP for short. PEPs don’t only contain the proposals, but they also reflect specifications for implementation, so you can sort of compare PEPs to the union of Java’s JEPs and JSRs.PEP 0 lists the index of PEPs.
You can find a lot of interesting information in PEP 8, including Pythonnaming conventions. If you read over them, you’ll see that these are slightly different from Java’s.
From its inception onwards, Python has always had a built-inread–eval–print loop (REPL). The REPL reads the shortest possible complete statement, expression, or block, compiles it into bytecode, and has it evaluated. If the evaluated code returns an object other than theNone object, it outputs an unambiguousrepresentation of this object. You’ll find an explanation ofNonelater in this tutorial.
Note: You can compare thePython REPL withJava’s JShell (JEP 222), which has been available since JDK 9.
The following fragment shows how Python’s REPL works:
>>>zero=int(0)>>>zero0>>>float(zero)0.0>>>complex(zero)0j>>>bool(zero)False>>>str(zero)'0'As you can see, the interpreter always attempts to show the resulting expression values unambiguously. In the example above, you can see how theinteger, floating point,complex,Boolean, andstring values are all displayed differently.
A difference between Java and Python involves theassignment operator (=). A regular Python assignment, which uses a single equals sign, is astatement rather than anexpression, which would yield some value or object.
This explains why the REPL doesn’t print the assignment to the variablezero: statements always evaluate toNone. The line following the assignment contains the variable expression,zero, to instruct the REPL to display the resulting variable regardless.
Note: Python 3.8 introduced anassignment expression operator (:=), which is also known as thewalrus operator. It assigns values to variables, but unlike a regular assignment, it evaluates them as if in an expression. That’s similar to the assignment operator in Java. Note, however, that it’s not completely interchangeable with the regular assignment statement. Its scope is actually quite limited.
In the REPL, theunderscore special variable (_) holds the value of the last expression, provided it’s notNone. The following fragment shows how you can use this special variable:
>>>2+24>>>_4>>>_+26>>>some_var=_+1>>>_6>>>some_var7After you assign the value7 tosome_var, the special variable_ still holds the value6. That’s because the assignment statement evaluates toNone.
An important characteristic of a programming language is when, how, and to what extent the language interpreter or compiler performstype verification.
Python is adynamically typed language. This means that the types of variables, function parameters, and function return values are checked at runtime rather than at compile time, unlike Java.
Python is at the same time astrongly typed language:
Here, you’ll explore how Python checks type compatibility at runtime and how you can make types compatible:
>>>40+"2"Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError:unsupported operand type(s) for +: 'int' and 'str'>>>40+int("2")# Add two numbers42>>>str(40)+"2"# Concatenate strings'402'>>>40*"2"# Repeat string "2" forty times'2222222222222222222222222222222222222222'You’ll notice that you can’t just add an integer value to a string value. This is guarded during runtime. When the interpreter detects a runtime error, it generates an exception. The REPL catchesException instances and shows thetraceback leading to the erroneous expression.
To resolve the issue, you convert one type to the other. If you want to add the two objects together as numbers, you convert the string representing the number into a plain number by using theint() constructor. If you’d like toconcatenate the two objects as strings instead, then you convert the number into a string by using thestr() constructor.
The last line of the Python session above shows another feature. By multiplying asequence with a number, you get the concatenated result of the original sequence, repeated by the given number.
Although Python is a dynamically typed language, it’s possible to provide the code withtype annotations.
During runtime, Python does nothing with these annotations except for making them available for introspection. However, static type checker tools exist that can detect inconsistencies between the type declarations and the actual use of type-annotated functions, classes, and variables.
Note: As stated above, the Python runtime makes type annotations available for introspection by the code. Some libraries make use of this information, such asFastAPI.
Type annotations help you detect errors at an early stage of the code development cycle. Especially in large-scale software projects, they help you make the code more maintainable and keep the codebase in good shape. You typically invoke a static type checker as part of the verification step in the build pipeline. Most IDEs make use of type annotations as well.
Unlike Java, Python’s reference implementation has no JIT compiler. By far, the most used Python implementation isCPython. This is also thereference implementation.CPython is a compiler and interpreter that’s been written in C and is pretty much available on every conceivable platform.
CPython loads a source file, which is called amodule, in two steps:
javac compiles a.java file into a.class file.Note: Unlike in Java, you can’t assume that the same Python bytecode will work with other Python implementations or even between different versions of the same Python implementation. It helps, however, in reducing the time needed to load a module.
Thecompiled modules are, if possible, stored in acache directory.
Unlike the mainstream Java VM implementations, CPython doesnot subsequently compile the bytecode intonative object code. There are, however, other Python implementations that work differently:
The list above isn’t exhaustive. The Python site contains a list ofalternative implementations and distributions.
As a Java developer, you might know the termoverloading frommethod overloading. While there’s a dynamic equivalent,@singledispatchmethod, available in Python that provides a somewhat similar functionality, there exists yet another kind of overloading in Python that you may find much more useful.
You can define new behavior of your custom-built classes for any eligible Python built-in functions and operators.
Note: In this context, you can consider eligible functions and operators to be those that allow you to overload their behavior.
Python provides an accessible way to achievefunction and operator overloading.
You can try this by definingspecially named methods in your class. The name of such a method starts and ends with two underscores, like.__len__() or.__add__(). An identifier having such a name is called adunder, short fordouble underscore (__).
When you call an eligible built-in function with an object for which a corresponding dunder method is present, Python delegates the behavior to this method. Likewise, when you use an operator for which one or more of the operands contain a corresponding dunder method, Python delegates the behavior to that method.
For example, you can define.__len__() to provide behavior to the built-inlen() function. Likewise, you can define.__add__() to provide behavior to the addition operator (+).
This feature makes it possible to apply the nice, expressive, and terse syntax of Python code not only to the standard objects but to custom objects as well.
In Java, you might have constructed lists by combining calls ofmap(),filter(), and lambda expressions. You can do the same in Python, using the same functions and techniques. Using these constructs doesn’t always result in the most readable pieces of code.
Python provides an elegant alternative syntax for this basic functional manipulation oflists and other collections. You’d uselist comprehensions for lists and other kinds of comprehensions for other collections. If you want to know more about comprehensions in Python, then you can explorewhen to use a list comprehension.
In Java, not everything is an object, despite the fact that the only place where you can put your code is inside a Java class. For example, the Java primitive42 isn’t an object.
Just like Java, Python also fully supports an object-oriented style of programming. Different from Java is thateverything is an object in Python. Some examples of Python objects are:
Because they’re objects, you can store all of these in variables, pass them around, and introspect them at runtime.
Note: As you read above, classes are objects. Since objects are instances of classes by definition, classesmust be instances of something as well.
Indeed, these are instances of ametaclass. The standard metaclass istype, but you can create alternativemetaclasses, usually by deriving fromtype, to alter the way classes are created.
Metaclasses, combined with the ability to overload built-in functions and operators, are part of what makes Python a versatile programming toolkit. They allow you to create your own programmable universe of additional or alternative behavior of classes and instances.
Despite the differences, you’ve probably also spotted some similarities between Java and Python already. That’s because Python and Java were both inspired by the C programming language. During your continuing exploration of Python, you’ll discover a lot more similarities to Java.
Python is aclass-based,object-oriented programming language, which is also one of the main features of Java. However, the set of object-oriented features differ between both languages and to address these in sufficient detail deserves a tutorial of its own.
Fortunately, you can dig deeper intoobject-oriented programming in Python vs Java to get an overview of the differences between Java and Python regarding object-oriented programming constructs. You can also check out an overview ofobject-oriented programming in Python to expand your knowledge about this topic.
One aspect where you might notice the languages’ shared heritage is in how they use operators. Many of them have the same meaning in both languages.
To start off, compare the well-known arithmetic operators in Java vs Python. The addition operator (+), subtraction operator (-), multiplication operator (*), division operator (/), and modulo operator (%) have almost the same purpose in both languages—except for the division operator on integer-like operands.
The same holds true for thebitwise operators: the bitwise OR operator (|), the bitwise AND operator (&), the bitwise XOR operator (^), and the unary bitwise NOT operator (~), as well as the bitwise shift operators for left shift (<<) and right shift (>>).
You can use the square bracket syntax ([]) in Python to access an element of a sequence, just like how you can work with Java’sarray access.
The later sections on data types provide more detail on these and some additional operators. Or, if you want to know more about them right now, you can read aboutoperators and expressions in Python.
Initially, Python offered string formatting functionality based on how theprintf family of functions handles this in the C programming language. This is similar to Java’sString.format(). In Python, the% operator performs this function. The left-hand side of the operator contains the format string, and the right-hand side contains either atuple of positional parameters or adictionary of keyed parameters.
Note: You’ll see more on tuples and dictionaries later on in this tutorial.
The following session shows some examples:
>>>"Hello,%s!"%"world"# %-style, single argument'Hello, world!'>>>"The%s is%d."%("answer",42)# %-style, positional'The answer is 42.'>>>"The%(word)s is%(value)d." \...%dict(word="answer",value=42)# %-style, key-based'The answer is 42.'More recently, Python has embraced other ways offormatting strings. One is to use the.format() string method, where the replacement fields are indicated with curly braces ({}). An example of this is"The {word} is {value}.".format(word="answer", value=42).
Since Python 3.6, you can also useformatted string literals, also known asf-strings. Suppose you have two variables in scope namedword andvalue. In that case, the expressionf"The {word} is {value}." renders the same string for you as the.format() example above.
The control flow constructs are similar when comparing Java vs Python. This means that you probably intuitively recognize many of the control flow constructs. On a more detailed level, however, there are also differences.
A Pythonwhile loop is similar to Java’s:
while(word:=input("Enter word: "))!="END":print(word)print("READY")Line by line, the code fragment copies the standard input to the standard output until the line equals"END". That line isn’t copied, but the text"READY" is written instead, followed by a newline.
You’ve probably noticed the added value of the walrus operator in a construct like this. Theprecedence of this assignmentexpression operator is the lowest of all operators. This means that you frequently need to add parentheses around the assignment expression when it’s part of a larger expression, just like in Java.
Note: Python has nodo {...} while (...) loop construct.
The Pythonfor loop is similar to the Java for-each loop. This means that if you want to iterate over a list of the first five Roman numerals, for example, you could code it using a similar logic:
>>>roman_numerals="I II III IV V".split()>>>roman_numerals['I', 'II', 'III', 'IV', 'V']>>>fornumeralinroman_numerals:...print(numeral)...IIIIIIIVVYou might notice that usingstr.split() is a convenient way to create a list of words.
Note: It’s not only alist instance that you can iterate over this way, but anyiterable.
Occasionally, you might need a running counter instead. In that case, you’d userange():
>>>foriinrange(5):...print(i)...01234In this example,i references the next value of the requested range with every iteration. That value is subsequently printed.
In the rare case where you want to iterate over a collection and at the same time want to have a running counter alongside it, you can useenumerate():
>>>fori,numeralinenumerate("I II III IV V".split(),start=1):...print(i,numeral)...1 I2 II3 III4 IV5 VThe example above shows the functionality of the two preceding examples combined in one single loop. By default, the accompanying counter starts at zero, but with the optional keyword argumentstart, you can specify another value.
Note: Check outPythonenumerate(): Simplify Loops That Need Counters if you want to know more about Python loops andenumerate().
Python also understands thebreak andcontinue statements.
Another control flow construct similar to Java is theif statement:
>>>forninrange(3):...ifn<=0:...adjective="not enough"...elifn==1:...adjective="just enough"...else:...adjective="more than enough"...print(f"You have{adjective} items ({n:d})")...You have not enough items (0)You have just enough items (1)You have more than enough items (2)As demonstrated above, the Pythonif ... else construct also supports anelif keyword, which is helpful because there’s no plainswitch ... case statement.
Note: The recently released Python 3.10 version contains a new feature namedstructural pattern matching, which introduces thematch andcase keywords, but it behaves quite differently from Java’sswitch statement.
This new language feature is inspired by thepattern matching statement of Scala, which is another programming language running on the JVM.
While many coding constructs look similar on the surface, there are still many differences. For example, Python loops, as well asexception catch constructs, support anelse: part. Furthermore, Python provides awith statement for context managers.
In the following subsections, you’ll find a condensed overview of Python’s standard types. The focus is on where these types or their associated operators differ from Java or how they compare to the corresponding Java collection class.
Python offers a variety of numeric types to choose from to suit your particular field of application. It has three numeric types built in:
| Type | Type name | Example literal |
|---|---|---|
| Integer | int | 42 |
| Floating-Point | float | 3.14 |
| Complex | complex | 1+2j |
If you compare both languages, then you’ll find that Python integers can contain arbitrary long values only limited by the amount of (virtual) memory your machine has available for you. You can think of them as an intelligent blend of fixed-precision native integers—or primitive integer types, as Java calls them—and Java’sBigInteger numbers, with the following consequences:
By using the prefixes0x,0o, and0b, you can specify the Python integers as hexadecimal, octal, and binary constants, respectively.
Note: This means that octal numbers arenot prefixed with just one or more leading zeros (0), which is different from Java.
Comparing well-known arithmetic operators+,-,*,/, and% in Java vs Python, they have the same meaning in both languages, except for the division operator on integer-like types. Thetruediv operator (/) applied onint operands yields afloat value in Python, which is different from Java. Python has thefloordiv operator (//) for division that rounds down to the nearest integer, comparable to the division operator (/) in Java:
>>>11/4# truediv2.75>>>11.0//4# floordiv, despite float operand(s)2.0Furthermore, Python provides the double-asterisk operator (**) for exponentiation as an alternative to the two-argumentpow() function. Thematmul operator (@) is reserved as an additional operator for types provided by external packages, intended as a convenience notation for matrix multiplication.
Both Python and Java adopted thebitwise operators from the C programming language. This means that the bitwise operators (|,&,^, and unary~) have the same meaning in both programming languages.
If you want to use these operators on negative values, then it’s good to know that in Python, integers are represented astwo’s complement values in a conceptually infinite large space to hold the bits. This means that negative values conceptually have an infinite amount of leading1 bits, just like positive numbers conceptually have an infinite amount of leading0 bits:
>>>bin(~0)'-0b1'>>>bin(~0&0b1111)# ~0 is an "infinite" sequence of ones'0b1111'The code fragment above indicates that regardless of the value you choose, if you bitwise-AND this value with the constant~0, then the resulting value is equal to the chosen value. This implies that the constant~0 conceptually is an infinite sequence of1 bits.
Thebit-shift operators (<< and>>) are also available. There is, however, no equivalent of Java’s bitwisezero-fill right shift operator (>>>), since that makes no sense in a number system with arbitrary long integers. There’s nomost significant bit within reach. Another difference between both languages is that Python doesn’t allow shifting bits with a negative shift count.
The Python standard library provides other numerical types as well. There’sdecimal.Decimal for decimal fixed-point and floating-point arithmetic, which is comparable to Java’sBigDecimal. There’s afractions.Fraction class for rational numbers, which is comparable toApache Commons Math Fractions. Note that these types arenot classified as built-in numeric types.
Sequence types are containers in which you can access their elements using integer indices.Strings andbyte sequences are also sequence types. These are presented a few sections later. Python has three basic sequence types built in:
| Type | Type name | Example literal |
|---|---|---|
| List | list | [41, 42, 43] |
| Tuple | tuple | ("foo", 42, 3.14) |
| Range | range | range(0, 9, 2) |
As you can see, the syntactic difference between list and tuple initializers are the square brackets ([]) versus the parentheses (()).
A Pythonlist is similar to Java’sArrayList, and it’smutable. You typically use this kind of container for a homogeneous collection, just like in Java. In Python, however, it’s possible to store objects of unrelated types.
Atuple, on the other hand, is more similar to animmutable version of aPair-like class in Java, except it’s for an arbitrary number of entries instead of two. Empty parentheses (()) denote an empty tuple. A construct like(3,) denotes a tuple containing a single element. In this case, the single element is3.
Note: Did you notice the peculiar syntax for atuple with just one single element? See the following session to spot the difference:
>>>(3,)(3,)>>>type(_)<class 'tuple'>>>>(3)3>>>type(_)<class 'int'>If you hadn’t added the trailing comma, then the expression would just be interpreted as an object inside parentheses.
Arange yields a sequence of numbers that you typically use in loops. You’ve seen an example of this earlier in this tutorial. If you want to learn more about ranges in Python, you can check outthis guide to the range() function.
To select anelement from a sequence, you can specify the zero-based index between square brackets, as insome_sequence[some_index]. Negative indices count backward from the end, so-1 denotes the last element.
You can also select aslice from a sequence. This is a selection of zero, one, or more elements, yielding an object of the same kind as the original sequence. You can specify astart,stop, andstep value, also known as the stride. An example of slicing syntax issome_sequence[<start>:<stop>:<step>].
All these values are optional, and practical defaults are taken when they’re not otherwise specified. Reading aboutlists and tuples in Python will be helpful if you want to know more about lists, tuples, indices, and slices.
For positive indices, Python syntax is similar to how youselect elements in Java arrays.
You can concatenate most sequences using the plus sign operator (+) and repeat them by using the asterisk operator (*):
>>>["testing"]+["one","two"]*2['testing', 'one', 'two', 'one', 'two']You can’t accomplish concatenation or sequence repetition with ranges, but you can slice them. For example, try outrange(6, 36, 3)[7:2:-2] and consider what you get as a result.
A dictionary in Python,dict, is similar to Java’sLinkedHashMap. The syntax of a dict initializer constant is a sequence of comma-separatedkey: value entries between curly braces ({}). An example of this is{"pi": 3.14, "e": 2.71}.
To select an element from a dict or any othermapping, you can specify the key between square brackets ([]), as inmath_symbols["pi"]. Both keys and values can be any object, but keys need to behashable, which means that they’re usuallyimmutable—or should behave like immutable objects, at least. Keys don’t necessarily need to be all of the same type, although they usually are. The same applies to values.
For additional info, you can read more aboutdictionaries in Python or check out the Python documentation onmapping types.
Python also providessets. You can initialize a set with a syntax like{"pi", "e"} or by using theset() constructor syntax, using an iterable as an argument. To create an empty set, you use the expressionset() since the literal{} was already given to dictionaries.
Sets use hashing in the underlying implementation. When you iterate over a set, take into account that the items will appear in apparently random order, just like in Java. Moreover, the order might even change between distinct Python invocations.
Some operators have been overloaded for operations on sets. For details, you can read more aboutsets in Python.
Just like in Java, strings in Python are immutable sequences of Unicode elements. String literals are specified between double quotes ("), or you can also specify them between single quotes ('), which is different from Java.
Two examples of strings are"foo" and'bar'. The different quotation marks don’t necessarily have any different meaning when defining a string. You should note, however, that if you’re using any quotation marks themselves as part of the string, you’ll have to escape them if they also happen to be the delimiters of the string.
Like in Java, the backslash (\) in Python is the character that introduces anescape sequence. The Python interpreter recognizes escape sequences also known in Java, like\b,\n,\t, and a few additional ones from the C programming language.
By default, Python assumes UTF-8 encoding of your Python source files. This means that you can put a Unicode literal directly in a string, like in the case of"é". You can also use the 16- or 32-bit hexadecimal representation of its code point. For"é", you would do this by using the\u00E9 or\U000000E9 escape sequences. Note the difference between the lowercase\u and uppercase\U escape sequences. Finally, it’s also possible to provide its Unicode description, like\N{Latin Small Letter E with acute}.
You can use Unicode characters even in Python identifiers, but then there’s the question of whether or not that’s an advisable thing to do.
In case you’re prefixing the string withr, like inr"raw\text", then the backslash loses its special meaning. This is especially convenient when you want to specifyregular expressions.
You can alsotriple-quote your strings as a convenient way to create multiline strings, like in the following example:
>>>s="""This is a... multiline... string.... """...>>>forlineins.splitlines():...print(repr(line))...'This is a'' multiline'' string.'' 'You can compare this type of string with Javatext blocks (JEP 378), although with other syntactic restrictions and with another preservation of whitespace (tabs, spaces, and newlines).
Within Java, if you need to storebinary data as opposed totext, you’d probably useByteBuffer, which gives you mutable objects. Within Python,bytearray objects provide similar functionality.
Unlike Java, Python also offers abytes type to store immutable binary data. Bytes literals look very similar to string literals, except you prefix the literal with ab. Strings contain an.encode() method to convert them to a sequence of bytes, and abytes object contains a.decode() method to convert it to a string:
>>>bytes(4)# Zero-filled with a specified lengthb'\x00\x00\x00\x00'>>>bytes(range(4))# From an iterable of integersb'\x00\x01\x02\x03'>>>b="Attaché case".encode()# Many different codecs are available>>>bb'Attach\xc3\xa9 case'>>>b.decode()# Decode back into a string again'Attaché case'If the codec isn’t specified, the default UTF-8 codec is used for encoding strings and for decoding bytes. When you need to, you can choose from a largelist of codecs that provide all sorts of text and bytes conversions.
Pythonbytes objects also have a.hex() method that produces a string that will list the contents as hexadecimal. For the reverse operation, you can use the.fromhex()class method to construct abytes object from a hexadecimal string representation.
False andTrue are the twobool instance objects in Python. In anumeric context,True evaluates to1 andFalse to0. This means thatTrue + True evaluates to2.
The Boolean logical operators in Python are different from Java’s&&,||, and! operators. In Python, these are the reserved keywordsand,or, andnot.
You see this summarized in the table below:
| Java | Python | Description |
|---|---|---|
a && b | a and b | logical and |
a || b | a or b | logical or |
!a | not a | logical not |
Similar to Java, there’s a short-circuiting evaluation behavior of the Boolean operatorsand andor, where the Python interpreter lazily evaluates the operands left to right until it can determine the truthiness of the whole expression.
Another similarity to Java is that the interpreter yields thelast evaluated subexpression as the outcome. Consequently, you should be aware that the outcome of anand oror expression does not necessarily yield abool instance object.
All Python objects either have afalsy ortruthy value. In other words, when you convert Python objects tobool, the outcome is clearly defined:
0 convert toFalse, andTrue otherwise.False, andTrue otherwise.None object converts toFalse as well.True.Note: User-defined classes can provide a.__bool__() dunder method to define the truthiness of their class instances.
If you want to test whether acontainer or string is non-empty, then you simply provide that object in a Boolean context. This is regarded to be aPythonic approach.
Check out the following different ways to check for a non-empty string:
>>>s="some string">>>ifs!="":# Comparing two strings...print('s != ""')...s != "">>>iflen(s)!=0:# Asking for the string length...print("len(s) != 0")...len(s) != 0>>>iflen(s):# Close, but no cigar...print("len(s)")...len(s)>>>ifs:# Pythonic code!...print("s")...sIn the last example, you just provide the string in a Boolean context. If the string isn’t empty, then it evaluates to true.
Note: The above doesn’t mean to imply that it’s Pythonic to rely on the implicitbool conversion for all kinds of types. The section below onNone addresses this in more detail.
You can follow theWrite More Pythonic Code learning path if you want to know more about the most typical Python constructs.
In Python, you code theconditional expression, written in Java with theconditional operator (? :), as an expression with the keywordsif andelse:
| Java | Python |
|---|---|
cond ? a : b | a if cond else b |
Consider an example of this type of expression in Python:
>>>forninrange(3):...word="item"ifn==1else"items"...print(f"Amount:{n:d}{word}")...Amount: 0 itemsAmount: 1 itemAmount: 2 itemsThe REPL outputs"item" only whenn equals1. In all other cases, the REPL outputs"items".
In Python,None is a singleton object that you can use to identifynull-like values. In Java, you’d use the literalnull for similar purposes.
The most frequent use ofNone within Python is as a default parameter value within function or method definitions. Furthermore, functions or methods that don’t return any value actually return theNone object implicitly.
In general, it’s regarded as acode smell when you rely on the implicit conversion ofNone in a Boolean context because of the risk that you’ll code unintentional behavior for other kinds of objects that happen to return a falsy value.
Consequently, if you want to test whether an object really is theNone object, then you should do that explicitly. Because there’s only oneNone object, you can do that by using the object identity operatoris or the opposite operatoris not:
>>>some_value="All"orNone>>>ifsome_valueisNone:...print(f"is None:{some_value}")>>>ifsome_valueisnotNone:...print(f"is not None:{some_value}")...is not None: AllKeep in mind that the wordnot here is an inseparable part of theis not operator, and it notably isn’t the same as the logicalnot operator. In this example, the string"All" has a truthy value in a Boolean context. You may also recollect that theor operator has this short-circuiting behavior and just returns the last expression as soon as the outcome is known, which is"All" in this case.
Java offers its standard container types through itscollections framework.
Python takes a different approach. It offers the basic container types that you’ve explored earlier in this section as built-in types, and then Python’s standard library provides some more container data types through thecollections module. There are many useful examples of container types that you can access through thecollections module:
namedtuple provides tuples where you can also access the elements through field names.deque provides double-ended queues with fast append and removal at both ends of the collection.ChainMap lets you fold multiple mapping objects into a single view on the mapping.Counter provides a mapping for counting hashable objects.defaultdict provides a mapping that calls a factory function to supply missing values.These data container types have been implemented just in plain Python.
At this point, you have a good foundation for understanding the similarities and differences between the features, syntax, and data types of Java vs Python. Now it’s time to take a step back and explore the available Python libraries and frameworks and find out how suitable they are for specific use cases.
You can use Python in many areas of use. Below you’ll find some of these areas, together with their most useful and popular related Python libraries or frameworks:
argparse provides functionality to create a command-line argument parser.Python also has some noteworthy tools related toquality assurance:
unittest library.The lists above are only a small selection of the many packages and frameworks available. You can browse and search the Python Package Index (PyPI) to find just that special package you’re looking for.
Often, you want to choose a programming language for one use case and a different programming language for another use case. When comparing Java vs Python, you should take the following aspects into consideration:
For certain usages, such as data modeling, analytics, machine learning, and artificial intelligence, execution speed really matters. The popular third-party packages created for this functionality are defined in a programming language that’s compiled to native code. For these areas, Python seems to be the most logical choice.
In this tutorial, you got acquainted with Python and you got a clear picture of the properties of this programming language. You’ve explored the similarities and differences between Java and Python.
You now have some experience for quickly getting started with Python. You also have a good foundation for understanding which situations and for which problem domains it’s useful to apply Python, as well as an overview of what helpful resources you can look to next.
In this tutorial, you learned about:
Maybe you’re sure that you’ll be working more with Python in the future, or maybe you’re still deciding whether to dig deeper into the language. Either way, with the information summarized above, you’re well equipped to explore Python and some of the frameworks introduced in this tutorial.
When you’re ready to learn more about Python and its packages, there’s a large collection of resources available on the web:
Now that you’ve gotten an idea of what kind of programming language Python actually is, you’re hopefully getting enthusiastic about it and thinking about picking it up for your next project, be it small or large. Happy Pythoning!
🐍 Python Tricks 💌
Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

AboutJan-Hein Bührman
Jan-Hein is a software developer who witnessed Python's first baby steps up very close. While working in different software development roles, he always kept an eye on Python's development. He's now back at the work he loves most: Python programming!
» More about Jan-HeinMasterReal-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
MasterReal-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students.Get tips for asking good questions andget answers to common questions in our support portal.
Keep Learning
Already have an account?Sign-In
Almost there! Complete this form and click the button below to gain instant access:

Get the Python Cheat Sheet (Free PDF)
Get aPython Cheat Sheet (PDF) and learn the basics of Python, like working with data types, dictionaries, lists, and Python functions:
