Create a gist now

Instantly share code, notes, and snippets.

@Atlas7 /js_vs_py.md
Last active May 15, 2017

What would you like to do?
Concatenate elements within an array / list - JavaScript vs Python

Say we want to concatenate elements within a JavaScript array (or Python list). i.e.

  • Input: an array that looks like this ['hello', 'world', '123', '!!!']
  • Process: concatenate the string elements within the array
  • Output: hello world 123 !!!

This post shows the similarity (and difference) of the JavaScript and Python syntax. (in case you start using JavaScript but from a Python background. Or vice versa, start using Python but from a JavaScript background)

JavaScript Solution

Pay attention to Step 3 - compare this to the Python version.

// (Step 1) define an array
const words = ['hello', 'world', '123', '!!!']

// (Step 2) define a string delimiter
const delimiter = ' '

// (Step 3) concatetenate elements in the array and form a long string
const sentence = words.join(delimiter)

// (Step 4) print it to terminal
console.log(sentence)
// -> hello world 123 !!!

Python Solution

Pay attention to Step 3 - compare this to the JavaScript version.

# (Step 1) define a list
words = ['hello', 'world', '123', '!!!']

# (Step 2) define a string delimiter
delimiter = ' '

# (Step 3) concatetenate elements in the array and form a long string
sentence = delimiter.join(words)

# (Step 4) print it to terminal
print(sentence)
# -> hello world 123 !!!

The difference in syntax:

Note the slight difference in syntax in Step 3. (Let's called a JavaScript array a "list" for now, for ease of visualizing the difference in syntax)

  • In JavaScript, we do: list.join(string)
  • In Python, we do: string.join(list)

See that "flip" in syntax (in the order of list and string)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment