Analogs in Python and JavaScript. Part one

Hi, Habr! I present to your attention the translation of the article "Equivalents in Python and JavaScript. Part 1" .


Although Python and Javascript are quite different, there are many similarities that any full-stack developer should be aware of. In this series of 4 articles, we will see what is common in both languages, and consider a number of known problems as well as ways to solve them.


This is not a reference book, there will not be basic information about the types of variables, if-ahs and cycles.
But we will look at more complex data structures and operations using them using Python and Javascript.


I will also illustrate this with examples from practice.


This series will be interesting for back-end vendors using Django, Flask or any other Python-framework who want to learn more about modern Javascript. On the other hand, these articles will be useful for front-endenders who want to better understand how the backend works, or even write a website on Django.


The remaining articles in this series are:


  1. Part Two : JSON, regulars, errors, exceptions
  2. Part three : modern Python and JS: string patterns (f-strings), list unpacking, lambda functions, list iterations, generators, sets.
  3. The fourth part is the function arguments, creating and working with classes, inheritance, setters getters, and class properties.

Cast to type


Let's start by casting the string to a whole. In Python, everything is simple and straightforward:


number = int(text)

But in JS you have to explain to which system you are going to convert to - decimal, octal, hexadecimal or binary:


number = parseInt(text, 10);

To use the usual decimal system, we pass 10 as the second argument to the parseInt () function. 8 for octal, 16 for hexadecimal, or 2 for binary. If the second parameter is omitted, the number starts from zero and you use an outdated browser, the line with the text will be perceived as an octal system:


parseInt('012') == 10// в некоторых старых браузерахparseInt('012', 10) == 12

Conditional assignment


Although Python and JS use different syntaxes for this, this operation is popular in both languages. It is popular because in one expression you can assign different values ​​for both the True and False cases.
Starting in Python 2.7, conditional assignment looks like this:


value = 'YES'if positive == Trueelse'NO'

In JavaScript, conditional assignments are made using the ternary operator ?, as well as in C, C ++, C #, Java, Ruby, PHP, Perl, Swift, and ActionScript:


value = positive === true? 'YES': 'NO';

Accessing an object property by property name


The usual way to access an object property in both Python and JS is the same:


obj.color = 'YELLOW'

And what if the property name is enclosed in a string variable? For example, the name property may be obtained from a list of properties or property name is made up of two string variables "title" + land_code.
In Python, for this there are functions getattr()and setattr():


attribute = 'color'
value = getattr(obj, attribute, 'GREEN')
setattr(obj, attribute, value)

In JS, you can treat an object as a dictionary and pass the name of the property in square brackets:


attribute = 'color';
value = obj[attribute] || 'GREEN';
obj[attribute] = value;

In order to get the default value in case a property with that name does not exist, in Python the function getattr()has a third parameter for this. In JS, if the requested property is missing, the function will return undefined. It can be compared by an operator ORwith a default value - this is standard practice in JS - such a method can be found in many frameworks and libraries.


Access to the dictionary by key


Similar to the above. The key is standardly indicated in square brackets in both languages:


dictionary = {}
dictionary['color'] = 'YELLOW'

For access by key in Python, standard syntax with square brackets is used; however, if such a key is missing, it will cause an exception with an error KeyError.
More flexible is the method get()that returns Nonein the absence of a key. You can also pass the value that will be returned if the key is missing:


key = 'color'
value = dictionary.get(key, 'GREEN')

In JS, you can do the same trick with the property of an object — ORwith a default value:


key = 'color';
value = dictionary[key] || 'GREEN';

Slices: Lists and Strings


Python has an operator [:]for obtaining parts of a list, tuple, or similar structures. An example with an object of type Django QuerySets:


items = [1, 2, 3, 4, 5]
first_two = items[:2]      # [1, 2]
last_two = items[-2:]      # [4, 5]
middle_three = items[1:4]  # [2, 3, 4]

JS has a method slice()with the same effect:


items = [1, 2, 3, 4, 5];
first_two = items.slice(0, 2);     // [1, 2] 
last_two = items.slice(-2);        // [4, 5]
middle_three = items.slice(1, 4);  // [2, 3, 4]

But do not confuse with the method splice()that changes the original array!


In Python, the operator [:]also applies to strings:


text = 'ABCDE'
first_two = text[:2]      # 'AB'
last_two = text[-2:]      # 'DE'
middle_three = text[1:4]  # 'BCD'

In JS, strings also have a method slice():


text = 'ABCDE';
first_two = text.slice(0, 2);    // 'AB'
last_two = text.slice(-2);       // 'DE'
middle_three = text.slice(1, 4); // 'BCD'

List operations


In programming, it is often necessary to collect and analyze a sequence of elements. In Python, lists are usually used for this, and in Javascript, arrays are used. They have similar syntax and operations, but methods for adding and deleting elements are different.


We combine two lists, add one element to the end, add one element to the beginning, get and delete an element at the beginning, get and delete an element from the end, and delete a specific element by index.
Python:


items1 = ['A']
items2 = ['B']
items = items1 + items2  # items == ['A', 'B']
items.append('C')        # ['A', 'B', 'C']
items.insert(0, 'D')     # ['D', 'A', 'B', 'C']
first = items.pop(0)     # ['A', 'B', 'C']
last = items.pop()       # ['A', 'B']
items.delete(0)          # ['B']

Same in javascript:


items1 = ['A'];
items2 = ['B'];
items = items1.concat(items2);  // items === ['A', 'B']
items.push('C');                // ['A', 'B', 'C']
items.unshift('D');             // ['D', 'A', 'B', 'C']
first = items.shift();          // ['A', 'B', 'C']
last = items.pop();             // ['A', 'B']
items.splice(0, 1);             // ['B']

Connecting rowsets


Connect a set of string elements into a single line using a space, comma or a newline in the form of a connecting character.


In Python, this is the string method join()that takes a list or a tuple as an argument. For the uninitiated (in Python syntax) it may seem strange to start an expression with a separator, but after regular use you will get used to this form of writing:


items = ['A', 'B', 'C']
text = ', '.join(items)  # 'A, B, C'

In JS, arrays have a method join()with a separator as an argument:


items = ['A', 'B', 'C'];
text = items.join(', ');  // 'A, B, C'

Summarize


  • Lists and tuples in Python correspond to arrays in Javascript.
  • Dictionaries (dictionaries) in Python correspond to objects (objects) in Javascript.
  • The lines in Python are similar to the Javascript lines.
  • You need to bring a string to a number in Javascript with caution, remembering the number systems.
  • Single-line conditional expressions exist in both languages.
  • Combining sequences of strings ( ' '.join) in Python discourages the uninitiated in syntax, but you get used to it quickly.

In the next series, we will look at creating and parsing JSON, regular expressions, and working with errors and exceptions!


Also popular now: