Analogs in Python and JavaScript. Part three

Original author: Aidas Bendoraitis aka archatas
  • Transfer

Continuing to translate a series of articles about analogs in Python and JavaScript

In previous releases, we relied on the syntax of the classic versions of Python (2.7) and JS based on ECMAScript 5. This time we will use the new functions that appeared in Python 3.6 and JS ECMAScript 6 standard.

ECMAScript 6 is a relatively new standard supported by most modern browsers . To use standard 6 in older browsers, you need Babel to translate modern JS6 designs into cross-browser support.

In today's article: variables in lines, unpacking of lists, lambda functions, iteration without indices, generators and sets (sets).

Content of other issues:

  1. The first part is a type conversion, a ternary operator, access to a property by property name, dictionaries, lists, strings, string concatenation
  2. The second part is serialization of dictionaries, JSON, regulars, errors and exceptions.
  3. This article
  4. The fourth part is the function arguments, creating and working with classes, inheritance, setter getters, and class properties.

Variables in strings

The traditional way of constructing strings with variables uses the concatenation of strings and variables:

name = 'World'
value = 'Hello, ' + name + '!\nWelcome!'

Such a record may seem scattered and poorly readable, you can also often make a mistake in the spaces around the words in the lines.

Starting from version 3.6 in Python and in JS ECMAScrip6 you can use string interpolation, or, in Python terms, f-strings. These are string patterns in which values ​​from variables are substituted.

In Python, f-strings are marked with f in front of quotes:

name = 'World'
value = f"""Hello, {name}!
price = 14.9
value = f'Price: {price:.2f} €'# 'Price: 14.90 €'

In JS, string patterns begin and end with a backquote (backtrick) `

name = 'World';
value = `Hello, ${name}!
price = 14.9;
value = `Price ${price.toFixed(2)} €`;  // 'Price: 14.90 €'

Note that templates can be both single and multiline.
In Python, you can set the formatting of variables.

Unpacking lists

In Python, and now in JS, there is an interesting opportunity to assign elements of a sequence to different variables. For example, we can assign three values ​​to three variables from the list:

[a, b, c] = [1, 2, 3]

For tuples, parentheses may be omitted.
The following example is very popular in Python as a way to exchange the values ​​of two variables:

a = 1
b = 2
a, b = b, a   # поменяли значения

In JS6 + it is also possible:

a = 1;
b = 2;
[a, b] = [b, a];  // поменяли значения

In Python, in case we have an indefinite number of elements in a list or a tuple, we can assign these elements to a tuple of variables in which the last few values ​​return as a list:

first, second, *the_rest = [1, 2, 3, 4]
# first == 1# second == 2# the_rest == [3, 4]

The same can be done in JS (ECMAScrip6):

[first, second, ...the_rest] = [1, 2, 3, 4];
// first === 1// last === 2// the_rest === [3, 4]

Lambda functions

Both Python and JS have fairly clear functionality for creating single-line functions. Such functions are called lambda functions. Lambdas are functions that take one or more arguments and return a calculated value. Usually, lambda functions are used when you need to transfer one function to another function as a callback or in the case when you need to process each element of the sequence.

In Python, you can define a lambda function using the keyword lambda:

sum = lambda x, y: x + y
square = lambda x: x ** 2

JS uses =>notation. If there are more than one arguments, they are placed in brackets:

sum = (x, y) => x + y;
square = x =>Math.pow(x, 2);

Iteration without indices

Many YaPs allow you to bypass arrays only using access to a particular element by index number and a cycle with an increment of this index.

for (i=0; i<items.length; i++) {

This is not a very beautiful record, and a bit complicated for beginners - this record does not look natural. In Python there is a beautiful laconic way of traversing the list:

for item in ['A', 'B', 'C']:

In modern JS, this is implemented using the operator for..of:

for (let item of ['A', 'B', 'C']) {

You can also bypass the string character in Python:

for character in'ABC':

And in modern javascript:

for (let character of'ABC') {


Both Python and modern JS allow you to define special functions that will look like iterators. For each call (iteration), they will return the next generated value from the sequence. Such functions are called generators.

Generators are usually used to obtain: numbers from a range, strings from a file, data page by page from the external API, Fibonacci numbers and other dynamically generated sequences.

Technically, generators look like normal functions, but instead of returning one value (and stopping work), they return one value and pause until the next call. They will generate the following values ​​from the list with each call until the end of the list is reached.

Consider an example on Python in which a countdown () generator is created which returns numbers from a given number to 1 in the reverse order (10,9,8, ..., 1):

defcountdown(counter):while counter > 0:
        yield counter
        counter -= 1for counter in countdown(10):

The same can be obtained in modern JS, but pay attention to * in the description of the function. This defines it as a generator:

function* countdown(counter) {
    while (counter > 0) {
        yield counter;
for (let counter of countdown(10)) {


We have already met with lists (lists), tuples (tuples), arrays (arrays). But there is another data type - sets. Sets are arrays of data in which each unique element is present only in a single copy. Set theory defines with sets such operations as union (union), intersection (intersection), and difference (difference), but we will not consider them now.

Create a set, add an element to it, check the existence of an element, get the total number of elements, go around the set by elements and delete one element using Python:

s = set(['A'])
s.add('B'); s.add('C')
'A'in s
len(s) == 3for elem in s:

The same on JS:

s = newSet(['A']);
s.has('A') === true;
s.size === 3;
for (let elem of s.values()) {


  • String patterns (f-lines) can improve readability and simplify the code, even in the case of multi-line objects.
  • You can bypass arrays, groups, or strings without using indexes.
  • Using generators, one can obtain sequences with an almost unlimited number of elements.
  • Using sets makes it easy to check the uniqueness of an element in an array.
  • Use lambda when you need small single-line functions.

In the next section, let's talk about function arguments, classes, inheritance, and properties.

Also popular now: