Thursday, June 24, 2021

List

Create Empty List
JS Python
let arr = [];
arr = []

Create list with size:
let arr = new Array(5);
arr = [None] * 5


Add an item at the end
arr.push(1);
arr.append(1);

Add an item at the begin:
arr.unshift(2);
arr.splice(0, 0, 2);
arr[:0]=[2]
arr.insert(0,2)

Add items inside:
arr.splice(2,0,3,4);
arr[1:0]=[3]

Add 2 arrays:
let arr3 = arr1.concat(arr2);
arr3 = arr1 + arr2
arr = [...arr, ...otherArr];
arr = [*arr, *otherArr]
arr.extend(otherArr)

Delete Items at the end
arr.pop();
arr.pop()

Delete items at the begin:
arr.splice(0,1);
arr[0:1]=[]

Delete items at the begin and return the deleted item
arr.shift();
arr.pop(0)

Delete Items inside (delete one item in index 1):
arr.splice(1,1);
arr[1:2]=[]
arr.pop(1)

Initial values:
arr = new Array(5).fill(0);
arr = [0] * 5

Range:
[...Array(5).keys()].map(i=>i+5);
list(range(5,10)

Get first item:
arr[0]
arr[0]

Get last item:
arr.slice(-1)[0];
arr[-1]

Get first N items:
arr.slice(0, N);
arr[0: N]

Is list?
Array.isArray(arr)
isinstance(arr, list)

String to list:
arr = s.split("");
arr = [...s];
arr = list(s)

List to string
s = arr.join("");
s = "".join(arr)

No comments: