Arrays / lists Flashcards
Add to end
list.append(value)
Remove from start
list.pop(0)
Remove from end
list.pop()
Remove from middle of array
del my_list[startIndex:endIndex]
Deletes a portion of the list in place, removing all elements from startIndex up to but not including endIndex
Length of list
len(my_list)
Map elements in a list, square each element
new_list = list(map(lambda x: x * 2, original_list))
Filter an array to create an array with elements over the value of 10
filtered_list = list(filter(lambda x: x > 10, original list))
Create an array of squares from an existing list with list comprehension
squares = [x**2 for x in list_variable]
Extend list with other list
list_variable.extend(another_list)
Count the number of times an element is in a list
list_variable.count(element)
Return the index of the first occurrence of an element, if not element not found value error
variable_list.index(element)
Reverse list in place
list_variable.reverse()
Check if element in list
if element in my_list:
if element not in my_list:
Slice and assign values in list
variable_list[1:3] = [7, 8]
Negative indexing, get last element
variable_list[-1]
Join array to make string
‘-‘.join(arr)
Sort list in place
my_list.sort()
my_list.sort(reverse=True)
my_list.sort(key=len)
Sort and return new list
sorted_list = sorted(my_list)
sorted(my_list, reverse=True)
Calculate sum of list
total_sum = sum(arr)
Remove element from array
arr.remove(element)