Introduction
In this article, I will talk about one of the most important and similar data structure in both Javascript and Python.
Javascript array (similar to Python list) is an object that lets you store multiple values in a single variable. For example, an array/list of countries would look like this: ['Nigeria', 'Canada', 'England', 'Mexico', 'China', 'India', 'Kuwait']. While this array/list is made up of only string data type, it can contain multiple data types.
Lets take a look at some commonly used methods when working with array/list in both Javascript and Python.
Creating array/list
let countries0 = ['Nigeria', 'Canada', 'England', 'Mexico', 'China', 'India', 'Kuwait'];
let countries1 = new Array('Nigeria', 'Canada', 'England', 'Mexico', 'China', 'India', 'Kuwait');
let countries2 = new Array()
countries1[0] = 'Nigeria';
countries1[1] = 'Canada';
countries1[3] = 'England';
Py:
countries = ['Nigeria', 'Canada', 'England', 'Mexico', 'China', 'India', 'Kuwait']
The list() function in python is used to convert from other types to list.
Adding an element to the end
Lets say, we want to add another country (Germany) to the end of the array/list. In js we use the push() function while in py we use the append() function.
countries.push('Germany');
countries.append('Germany')
Adding an element to the beginning
countries.unshift('USA');
countries.insert(0, 'USA')
Check if an value is an array or a list
Array.isArray(countries); // returns true if the object is an array
type(countries) == list # returns True if the object is a list
isinstance(countries, list)
Removing an element from the end
countries.pop();
countries.pop() # by default remove last item
del countries[-1] # -1 means the last index item
Removing an element from the beginning
countries.shift();
countries.pop(0)
del countries[0]
Finding an index of an element
countries.indexOf('India');
countries.index('India')
Remove item with by specific value
// JS has no direct function to do this, but it can be manipulated using filter() function as follow;-
var newCountries = countries.filter((value)=>value!='China');
countries.remove('India')
Check how many items are contained
countries.length
len(countries)
Remove all items
countries.length = 0
countries.splice(0, countries.length) // splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
countries.clear()
Conclusion
This is not in anyway an exhaustive list of operations you can perform with arrays and list in javascript and python respectively. However, with what you have learned here, you can now comfortably work with arrays/lists.
That is it!
No comments:
Post a Comment