Python for a Java developer [1]

I will share my learning curve and unthinkable points of python as a java developer.

Mehedee Hassan
3 min readJul 17, 2021

When I had started python, I already had 2years of experience in java. So it was very uncomfortable to get into the python world. In this series, I will explain things a java developer will never think about when coding.

Today [part 1] I will explain two topics ,

  1. The use of underscore ( _ )
  2. List Comprehension [Inline list operations]

USE OF UNDERSCORE(_):

Skipping a value:

We can skip a value assignment by using underscore in place of a variable name.For example.

For a list of element.
for a function.

We can skip multiple element using star(*) operator before underscore (_).Here we are skipping [2,3,4,5,6].

skipping [2,3,4,5,6].

For a list of tuples we can ignore key(considering first element as key) if we don’t need it ,like in the last two lines in the below image explains a function don’t need the keys of tuples so we skip it,

skipping keys of the list of tuples.

In Object Oriented Part:

Double leading and trailing underscore:

Few special methods use this format like,

  1. __init__ ,Constructor of the class
  2. __len__ , We override this method to return custom value for len(MyClassObject).
  3. __file__ ,Can give you the current python file location.
  4. __eq__ , is executed for any custom objects of Mycalass a and Myclass b, when a==b type expressions are executed. In a word you override __eq__ when you need any (==) operation is needed for your class.
double underscore methods.

Also, a single underscore before field’s name or a method’s name inside class indicates private field or method.In above example _a is a private field.

List Comprehension:

We use logical ,mathematical operation on a list to get a new list in a single line. Soooo.. convenient, if we understand it.

Logical operation

For a list of [1,2,3,4,5] we can set “G” for an element ,greater than 3 and set “S” for an element ,less than or equal to 3 in then modified new list.For example.

logical operation

Mathematical Operation

Here we square each element of list l containing [1,2,3,4,5].

mathematical operation

Unpacking List of Tuples

We can only take list of values or keys from list of tuples:

Nested List operation

We can perform nested list operation as shown below.Here we perform a matrix transpose[1].

matrix transpose.

Conclusion

This was a small overview of use of underscore and list comprehension feature of python.Please use python documentations for more deep knowledge[1][2].Hope you like it .

References

[1] https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

[2]https://docs.python.org/3/

--

--