Lists - List Methods
Lists - List Methods
Lists
List Methods
my_list = [1, 2, 3]
new_element = 4
my_list.append(new_element)
print(my_list)
challenge
append versus +
There is an important difference between append and the concatenation
operator (+). The + operator only combines two lists. The append method
can add a value of any data type to a list.
Pop
Translation: Pop (remove and return) the last element from the list
my_list.
my_list = [1, 2, 3, 4]
print(my_list)
print(my_list.pop())
print(my_list)
challenge
my_list = [1, 2, 3, 4]
print(my_list)
my_list.pop()
my_list.pop()
my_list.pop()
my_list.pop()
print(my_list)
popversus my_list[-1]
my_list[-1] returns the last element in a list. This does not modify the
original list. The pop method also returns the last element of a list, but it
always modifies the original list. The last element has been removed from
the list.
Optional Parameters
The pop method has optional parameters. That means if you do not put
anything between the parentheses, it will pop off the last element (index of
-1) in the list. If you want to remove a different element, put the element’s
index between the parentheses.
Optional Parameters
my_list = [1, 2, 3, 4]
delete = 0
print(my_list.pop(delete))
print(my_list)
challenge
List Insert
my_list = [1, 2, 3, 4]
my_list.insert(2, "Hi")
print(my_list)
challenge
List Remove
my_list = [1, 2, 3, 3, 4]
my_list.remove(2)
print(my_list)
challenge
Pop Remove
Removes an element Removes an element
Removes based on index Removes based on value
Returns the removed value Does not return anything
list_1 = [1, 2, 3, 4, 5]
list_1.pop()
print(list_1)
list_2 = [1, 2, 3, 4, 5]
list_2.remove(5)
print(list_2)
challenge
list_1 = [1, 2, 3, 4, 5]
print(list_1.pop())
list_2 = [1, 2, 3, 4, 5]
print(list_2.remove(5))
Count
my_var = 2
my_list = [2, "red", 2.0, my_var, "Red", 8 // 4]
print(my_list.count(2))
challenge
Index Method
challenge
challenge
Reverse Sort
The sort method has an optional parameter to sort a list in descending
order. Use reverse=True as the parameter to reverse sort a list.
Reverse Method
challenge