In Python Lists are used to store multiple items in a single variable. There are multiple built-in methods that you can use on lists or arrays in Python. Lists are one of 4 built-in data types in Python Programming. A list in Python is created by placing all the items inside square brackets [] , and is separated by commas.
# append() This method will adds an element at the end of the list us_states = ['New York', 'New Jersey', 'Delaware'] us_states.append('Virginia') print(us_states) #['New York', 'New Jersey', 'Delaware', 'Virginia'] us_west_cost_states = ['Los Angeles','San Francisco','Portland'] us_states.append(us_west_cost_states) print(us_states) #['New York', 'New Jersey', 'Delaware', 'Virginia', ['Los Angeles', 'San Francisco', 'Portland']]
# copy() This method will returns a copy of the list us_states = ['New York', 'New Jersey', 'Delaware'] us_states_cp = us_states.copy() print(us_states_cp) #['New York', 'New Jersey', 'Delaware', 'Virginia', ['Los Angeles', 'San Francisco', 'Portland']] print(id(us_states)) print(id(us_states_cp))
# count() This method will returns the number of elements with the specified value us_states = ['New York', 'New Jersey', 'Delaware'] print(us_states.count('New York')) #1
# extend() Add the elements of a list (or any iterable), to the end of the current list us_states = ['New York', 'New Jersey', 'Delaware'] us_west_cost_states = ['Los Angeles','San Francisco','Portland'] us_states.extend(us_west_cost_states) print(us_states)
# index() This method will returns the index of the first element with the specified value us_states = ['New York', 'New Jersey', 'Delaware'] idx = us_states.index('Delaware') print(idx)
# insert() This method will adds an element at the specified position us_states = ['New York', 'New Jersey', 'Delaware'] s_states.insert(0,'Virginia') print(us_states)
# pop() This method will removes the element at the specified position us_states = ['New York', 'New Jersey', 'Delaware'] var_pop = us_states.pop() print(var_pop)
#remove() This method will removes the first item with the specified value us_states = ['New York', 'New Jersey', 'Delaware'] us_states.remove('New Jersey') print(us_states) #['New York', 'Delaware']
#reverse() This method will reverses the order of the list us_states = ['New York', 'New Jersey', 'Delaware'] us_states.reverse() print(us_states)
# clear() This method will removes all the elements from the list us_states = ['New York', 'New Jersey', 'Delaware'] us_states.clear() print(us_states) # []
# sort() Sorts the list us_states = [ 'New Jersey','Delaware', 'New York'] us_states.sort() print(us_states) #['Delaware', 'New Jersey', 'New York']