Python 101 for JavaScript Developers (Part II — List/Array Methods Edition)

Intro

Hello! A little over a year ago, I wrote Part I (not known as Part I back then, but now it’s officially Part I!) as I went on my Python journey. And guess what, I stopped learning as many things had happened [that includes getting employed at my current job!]. Now, I am back to my Python journey with more JavaScript experience. In Part I, I mainly focused on syntax; in this article, I’d like to focus on methods. Let’s get to them!

Recall

In Part I, I have briefly covered List in Python and Array in JavaScript (#15). They are pretty much the same but different ways of calling something inside a []. For this article, I am very excited to focus on built-in methods for Python and JavaScript respectively. There are a few methods that are quite mind-blowing [Look out for mind-blowing emoji 🤯]and I wish those also exist in JavaScript!

10 differences between Python and JavaScript

  1. Adding items to list/array:append() vs push()

I remembered when I was reading some JavaScript articles, append is a word that got thrown around a lot while that keyword doesn’t exist in JavaScript. Essentially, both append() and push() have very similar syntax, which you includes the element you want to push to the list/array inside the parenthesis.

Code Sample:

# Python
my_list = ["python", "javascript", "c++"]
my_list.append("ruby")
print(my_list)
# ["python", "javascript", "c++", "ruby"]
// JavaScript
const myList = ["python", "javascript", "c++"];
myList.push("ruby");
console.log(myList);
// ["python", "javascript", "c++", "ruby"]

(Back to “You Made It!” section)

2. 🤯Removing specific items: remove() vs pop()/shift()/splice()/map()...

Note: pop() is also one of the Python built-in list methods, which we would discuss in the next point. [so as map(), but will not cover in this guide.]

This is one of the Python built-in methods that blows my mind. In JavaScript, if we want to remove a specific item, we will have to iterate the array or write multiple lines to retrieve that item to remove a specific item [9 Ways to Remove Elements From A JavaScript Array — Plus How to Safely Clear JavaScript Arrays]. That’s not the case in Python! If you want to remove banana , Python’s like, “LET’S REMOVE IT!” [Sorry Minions!!!]

Code Sample:

# Python
my_grocery_list = ["lettuce", "garlic", "banana", "apple"]
my_grocery_list.remove("banana")
print(my_grocery_list)
# ["lettuce", "garlic", "apple"]
// JavaScript [One of the methods to remove: `filter`]
const myGroceryList = ["lettuce", "garlic", "banana", "apple"];
const filteredList = myGroceryList.filter(ele => ele !== "banana");
console.log(filteredList);
// [ 'lettuce', 'garlic', 'apple' ]
Resource: GIF Tenor

Sorry Stuart! :(

(Back to “You Made It!” section)

3. pop() vs pop()

As mentioned above, we will talk about the usage difference for pop() for both Python and JavaScript respectively.

While in JavaScript, pop() means removing the last element from the array. Same goes to Python, however, with a small twist! You have an additional option to indicate the index of the element you want to remove. [Quick reminder: remove() takes in string].

# Python
minions = ["Bob", "Kevin", "Stuart"]
# remove the last element
minions.pop() #eeek sorry Stuart again!!
print(minions)
# ['Bob', 'Kevin']
# OR, remove a specific element by specifying the index
minions.pop(1) # removing the 2nd element
print(minions)
# ['Bob', 'Stuart']
// JavaScript
const minions = ["Bob", "Kevin", "Stuart"];
// You can only remove the last element with pop()
minions.pop();
console.log(minions);
// [ 'Bob', 'Kevin' ]

(Back to “You Made It!” section)

4. Finding the length of a list/array: len() vs length

This is pretty straightforward, but as a JavaScript developer, I think I would always accidentally write length() instead of len(). But yes, as you can already guess from the name, both methods returns the number of items in an object.

Code Sample:

# Python
top_gun_candidate = ["Iceman", "Maverick", "Goose", "Hollywood"]
len(top_gun_candidate) # 4
// JavaScript
const topGunCandidate = ["Iceman", "Maverick", "Goose", "Hollywood"];
const topGunLength = topGunCandidate.length;
console.log(topGunLength);
// 4

(Back to “You Made It!” section)

5. Counting the occurrences of a specific item: count() vs using for loop [C’mon JavaScript!]

This built-in list method is only available to Python, not JS. count() as it’s stated in the name that it counts the occurrences of a specific item in a list whilst in JavaScript, we’ll have to use for loop to do so.

Code Sample — Oh, wait! Looks like the minions are voting who’s going to be their leader! We got 3 candidates — Stuart, Bob, Kevin. Let’s see who got the most votes!

# Python
vote_for_minion_leader = ["Stuart", "Bob", "Stuart", "Kevin", "Stuart", "Kevin", "Bob", "Bob", "Stuart", "Kevin"]
# Vote for Stuart
stuart_vote = vote_for_minion_leader.count("Stuart")
print(stuart_vote) # 4
# Vote for Bob
bob_vote = vote_for_minion_leader.count("Bob")
print(bob_vote) # 3
# Vote for Kevin
kevin_vote = vote_for_minion_leader.count("Kevin")
print(kevin_vote) # 3
# Ah, looks like we have a winner! Congratulations to Stuart!// JavaSript - have to iterate with for loop
const voteMinionLeader = ["Stuart", "Bob", "Stuart", "Kevin", "Stuart", "Kevin", "Bob", "Bob", "Stuart", "Kevin"];
const voteCount = {};for (let i = 0; i < voteMinionLeader.length; i++) {
let candidate = voteMinionLeader[i];
if (!voteCount[candidate]) {
voteCount[candidate] = 1;
} else {
voteCount[candidate] += 1;
}
}
console.log(voteCount);
// { Stuart: 4, Bob: 3, Kevin: 3 }

Quick sidebar 🍸: You might notice I am using semicolons in JavaScript. You don’t have to use semicolons in JavaScript. Although it’s my personal strong preference to use semicolons, this is also a way to distinguish JavaScript syntax and Python syntax for this article. 😃

(Back to “You Made It!” section)

6. Wait 🤯, negative indexes is a thing??? <array>[-1] vs ????

The only way to get the last element of the array in JavaScript without knowing how many items is <array>[<array>.length — 1]. However, with Python, you can use negative index to retrieve the last element or second last or third last… and so on… elements! AH-MAZING!

# Python
call_sign_two = ["Hangman", "Rooster", "Payback", "Fanboy"]
# Retrieve the last element
last_element = call_sign_two[-1]
print(last_element)
# 'Fanboy'
# Retrieve the second last element
second_last_element = call_sign_two[-2]
print(second_last_element)
# 'Payback'
// JavaScript
const callSignTwo = ["Hangman", "Rooster", "Payback", "Fanboy"];
// Retrieve the last element
const lastElement = callSignTwo[callSignTwo.length - 1];
console.log(lastElement);
// Fanboy

Pretty cool, right?? Keep this in mind — we will revisit negative indexes in the next few points.

Speaking of cool 👆🏻

(Back to “You Made It!” section)

7. Adding elements to a certain index: insert() vs splice()

Note: splice() is one of Python built-in methods, but for string. However, splice() is only available to JavaScript as an array method.

If you want to add an elements anywhere in a(n) list/array, insert() will be your method in Python and splice() for JavaScript. There’s slight difference with Python and JavaScript. Let’s see how it’s done!

Code Sample [Slight spoiler alert!]:

# Python
top_gun_two = ["Maverick", "Rooster", "Phoenix", "Bob"]
# Hangman to the rescue, let's insert "Hangman" in between Rooster and Phoenix
top_gun_two.insert(2, "Hangman")
print(top_gun_two)
# ['Maverick', 'Rooster', 'Hangman', 'Phoenix', 'Bob']
// JavaScript
const topGunTwo = ["Maverick", "Rooster", "Phoenix", "Bob"];
// inserts at index 2 without replacing anything
topGunTwo.splice(2, 0, "Hangman"); // []
console.log(topGunTwo);
// [ 'Maverick', 'Rooster', 'Hangman', 'Phoenix', 'Bob' ]
// replaces 1 element at index 3 (i.e. "Phoenix") with "Fanboy"
topGunTwo.splice(3, 1, "Fanboy") // [ 'Phoenix' ]
console.log(topGunTwo);
// [ 'Maverick', 'Rooster', 'Hangman', 'Fanboy', 'Bob' ]

Despite the slight complexity, I like JavaScript splice method more as you can replace and insert new element whilst you can only insert new element in Python.

Quick sidebar 🍸: splice() has more functionalities than what I demonstrated above. Please refer to MDN for more usages. Also, splice() is immutable, i.e. it will modify the array as demonstrated above. If you’re looking for a method that doesn’t modify your array, slice() will be the method!

(Back to “You Made It!” section)

And speaking of slice…

8. Slicing an array: <array>[start:stop] vs splice()/slice()

Note: slice() is also one of the Python built-in method (Check out here), but will not discuss this in this article.

Python’s <array>[start:stop] start: the start of the index and end:which index you want to stop the slice, i.e. does not include in the slice. slice() in both languages does not mutate the original array/list.

Code Sample:

# Python
dog_breeds = ["german shepherd", "shiba inu", "labrador", "golden retriever", "greyhound", "irish doodle", "beagle"]
most_favorite_dog_breeds = dog_breeds[1:4]
print(most_favorite_dog_breeds)
# ['shiba inu', 'labrador', 'golden retriever']
# or leave the the right hand side of the `:` empty, it will slice from which index you indicate to the end of the list!
from_third_to_end = dog_breeds[2:]
print(from_third_to_end)
# ['labrador', 'golden retriever', 'greyhound', 'irish doodle', 'beagle']
# vice versa if leaving the left hand side empty
first_three = dog_breeds[:3]
print(first_three)
# ['german shepherd', 'shiba inu', 'labrador']

Remember we talked about negative indexes at #6? It’s time to revisit!

<array>[-n] will retrieve the n-th last element of the list. This can also be applied here! 🤯

dog_breeds = ["german shepherd", "shiba inu", "labrador", "golden retriever", "greyhound", "irish doodle", "beagle"]# negative index slice? LET'S GO
# from the third last element to the end
last_three = dog_breeds[-3:]
print(last_three)
# ['greyhound', 'irish doodle', 'beagle']
# from the third last element to the second last element
third_and_second_last = dog_breeds[-3:-1]
print(third_and_second_last)
# ['greyhound', 'irish doodle']

Bam! Things JavaScript cannot do! I’ve already demonstrated splice() in the previous point, so not going to show any code example.

(Back to “You Made It!” section)

Mid-to-end-article break

We’re 80% into this article. Hope y’all are feeling good at this point! I would always recommend you all to create your own array/list and try out these methods on your own! Feel free to call me out if some of these examples I put here are giving errors on your console. I am also testing the code on my end as well!

Screenshot from my terminal

9. Printing an array with a sequence of numbers: range() vs fill/map()/for loops

This range() feature unfortunately does not exist in JavaScript. That also explains why Python is a more popular language in data science/data analytics. To achieve that in JavaScript, you’ll have to use for loop or some engineers from a Stack Overflow post suggested to use Array(n).fill().map(some function) .

I am going to break down the range() syntax real quick:

range(start, stop, step)

start : start at 0 by default;

stop: stop at any number, which does not include;

step: the increment from the previous element

Code Sample:

# Python # this will print from 0 to 9
my_list = range(10)
print(my_list)
# range(0, 10)

Wait, why is it returning range(0, 10) , but not a list?? Well because range() creates a range object. If we want to create a list, there’s a built-in method called list , which would “translate” an object to a list we are familiar with.

Let’s try again!

# Python
print(list(my_list))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Let's print from 2 to 10!
starting_from_two = range(2, 11)
print(list(starting_from_two))
# [2, 3, 4, 5, 6, 7, 8, 9, 10]
# Do you have a favorite number? 7 is my fav :) Let's print from 7 to...70 with an increment of 7!
increment_of_7 = range(7, 77, 7)
print(list(increment_of_7))
# [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]

Quick sidebar 🍸: If you want to check the length of your range() , you don’t have to call list .

increment_of_7 = range(7, 77, 7)
length_of_seven = len(increment_of_7)
print(length_of_seven) # 10
increment_of_7_diff_5 = range(7, 77, 5)
length_of_seven_diff_five = len(increment_of_7_diff_5)
print(length_of_seven_diff_five) # 14

(Back to “You Made It!” section)

10. Sorting an list/array: sort()/sorted() vs sort()

There’s a slight difference between sort() and sorted() in Python. However, I will not dive deep in this article. Check out this great article from GeeksForGeeks! But no sweat, I will still demonstrate in this article 😄

In general, sorting is one of the basic built-in methods for if not all but almost all programming languages. They work quite similarly, except Python can take in an additional parameter for a descending order, while that is not the case for JavaScript (C’mon JavaScript!!)

# Python
my_numbers = [4, 7, 9, 100, 43, 76, 98, 1, 23, 30]
my_favorites = ["shiba inu", "coding", "rapunzel", "baking"]
# Ascending
# sort()
my_numbers.sort()
print(my_numbers)
# [1, 4, 7, 9, 23, 30, 43, 76, 98, 100]
my_favorites.sort()
print(my_favorites)
# ['baking', 'coding', 'rapunzel', 'shiba inu']
# sorted()
sorted_numbers = sorted(my_numbers)
print(sorted_numbers)
# [1, 4, 7, 9, 23, 30, 43, 76, 98, 100]
sorted_favorites = sorted(my_favorites)
print(sorted_favorites)
# ['baking', 'coding', 'rapunzel', 'shiba inu']
# Descending
# sort()
my_numbers.sort(reverse=True)
print(my_numbers)
# [100, 98, 76, 43, 30, 23, 9, 7, 4, 1]
my_favorites.sort(reverse=True)
print(my_favorites)
# ['shiba inu', 'rapunzel', 'coding', 'baking']
# sorted()
reverse_sorted_numbers = sorted(my_numbers, reverse=True)
print(reverse_sorted_numbers)
# [100, 98, 76, 43, 30, 23, 9, 7, 4, 1]
reverse_sorted_favorites = sorted(my_favorites, reverse=True)
print(reverse_sorted_favorites)
# ['shiba inu', 'rapunzel', 'coding', 'baking']

What I love about the sorting method in Python is that it does exactly what you’re expecting: ascending/descending numbers, because that’s not the case in JavaScript.

In JavaScript, the default sort order based upon their UTF-16 code units values (Reference: MDN). Not that I have solid understanding what UTF-16 code units actually means, besides knowing it can take more bytes per character than UTF-8 and each character is assigned to a specific value.

Therefore, for JavaScript, you have to take an extra step by adding first and second parameter as comparison if you’re sorting numbers.

// JavaScript
const numArr = [4, 7, 9, 100, 43, 76, 98, 1, 23, 30];
const strArr = ["shiba inu", "coding", "rapunzel", "baking"];
// Ascending order
numArr.sort((a, b) => a - b);
console.log(numArr);
// [
// 1, 4, 7, 9, 23,// 30, 43, 76, 98, 100// ]strArr.sort();
console.log(strArr);
// [ 'baking', 'coding', 'rapunzel', 'shiba inu' ]
// Descending order
numArr.sort((a, b) => b - a);
// [
// 100, 98, 76, 43, 30,// 23, 9, 7, 4, 1// ]strArr.sort().reverse();
console.log(strArr);
// [ 'shiba inu', 'rapunzel', 'coding', 'baking' ]

I had to Google how to sort strings in descending orders in JavaScript. Here’s the Stack Overflow post I used as reference.

(Back to “You Made It!” section)

BONUS 🎉 — zip() 🤯

zip() is useful when you want to aggregate elements from two or more iterable objects. It helps quickly solve problems, for instance, creating dictionaries. zip(*iterables) takes in two or more iterable objects and return a tuple.

engineer_names = ["Marie", "Eddie", "Al", "Jean Paul"]
engineer_ages = [20, 25, 21, 27]
result = zip(engineer_names, engineer_ages)

If you print result, you would see something like this <zip object at 0x7fed12377940> -> location of memory. If you recall we have briefly discussed the built-in list in Python at #9, don’t forget to add that if you want to see the list result.

print(list(result))
# [('Marie', 20), ('Eddie', 25), ('Al', 21), ('Jean Paul', 27)]

This built-in method quickly becomes one of my favorite Python built-in methods. It’s so cool!

More resources about zip() :

As I was researching whether there’s a similar feature in JavaScript, I came across this Stack Overflow post from 11 years ago. I found this comment pretty funny that I want to share to wrap up this article:

Final Thoughts

In comparison, Python has a lot more built-in methods and it’s quite a lot to remember. Regardless, I had so much fun learning Python and hope I can put this language in use and potentially work with both languages simultaneously to understand better the pros and cons of JS and Python.

And thanks CodeCademy for providing Python3 hands-on coding course. I learned all these methods from the course and wrote this article from my JavaScript experience perspective. Highly recommend to check that out!

And hey, FINALLY this is the end. My fellow JavaScript developers, how are we feeling about Python?

Please feel free to bookmark this article for your future reference if needed!

Last but not least,

Happy Coding!

Completely sidenote: I love The IT Crowd! 👆🏻

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Megan Lo

Megan Lo

Software Engineer | JavaScript | TypeScript | ReactJS