< previous | Table of Contents | next > |
8.5 LIST METHODS
INDEX() METHOD
The index()
method returns the index of the first occurrence of an element within the list. If the element is not found, a ValueError
is raised.
favorite_songs = ["Without Me", "Valge Mersu", "Tsirkus", "Baby"] index_of = favorite_songs.index("Valge Mersu") # Returns 1 which is the corresponding index
Here's an example in Thonny of what happens when the element cannot be found.
ADDING ELEMENTS TO A LIST
append()
adds the specified element to the end of the list.
favorite_songs.append("Holiday")
extend()
adds all list elements to the end of the current list.
favorite_songs.extend(["Roosiaia kuninganna", "The Real Slim Shady"])
insert()
inserts an item at the specified position, replaces the item that was there previously.
favorite_songs.insert(1, "The Real Slim Shady")
REMOVING ELEMENTS FROM A LIST
remove()
removes the first occurrence of an item in the list.
favorite_songs.remove(“Tsirkus”)
pop()
removes and returns an item at a given position, defaulting to the last position if no index is specified.
favorite_songs.pop() # Removes the last item from the list and returns it favorite_songs.pop(2) # Removes the third item from the list and returns it
SORTING LISTS
sort()
sorts the items in the list in ascending order.
numbers = [8, 2, 2, 1, 5, 9, 3] numbers.sort() print(numbers) # Outputs the list of numbers in an ascending order [1, 2, 2, 3, 5, 8, 9]
Python sorts lists of strings alphabetically while also considering the case of the string according to Unicode.
favorite_songs.sort() print(favorite_songs) # Outputs ['Baby', 'Tsirkus', 'Valge Mersu', 'Without Me']
When sorting lists of lists, Python compares the first elements of each inner list, then the second elements if the first are equal, and so forth.
list_of_lists = [[6, 4], [7, 8], [1, 3]] list_of_lists.sort() print(list_of_lists) # [[1, 3], [6, 4], [7, 8]]
REVERSING LISTS
The reverse()
method directly modifies the list to reverse the order of its elements. Note that no new list is created but rather thethe original list is changed.
numbers = [8, 2, 2, 1, 5, 9, 3] numbers.reverse() print(numbers) # Outputs the list but reversed [3, 9, 5, 1, 2, 2, 8]
You can also reverse a list using slicing. This does not alter the original list but instead creates a new list that is a reversed version.
numbers = [8, 2, 2, 1, 5, 9, 3] reversed_numbers = numbers[::-1] # Creates a new reversed list print(reversed_numbers) # Output: [3, 9, 5, 1, 2, 2, 8]
MAX(), MIN(), and SUM()
The max()
function returns the largest item in a list of two or more arguments.
print(max([1, 2, 3])) # Outputs 3 print(max("Hello world!")) # Outputs 'w' print(max(1, 2, 3, -4)) # Outputs 3
Conversly, min()
returns the smallest item in a list of two or more arguments.
print(min([1, 2, 3])) # Outputs 1 print(min('hello world')) # Outputs ' ' which is the space between the two words print(min(1, 2, 3, -4)) # Outputs -4
The sum()
function calculates the sum of the values provided from left to right.
print(sum([1, 2, 3])) # Outputs 6 print(sum([1, 2, 3], 10)) # Outputs 16
THE SPLIT() METHOD
The split()
method divides a string into a list of substrings based on a specific delimiter, such as a comma ,
, semicolon ;
, tab \t
, space ‘ ‘
, or newline \n
. If no delimiter is specified, then the method will split the string by whitespace.
Here’s a more detailed example of using the split method to parse a string:
items = "New Balance,155; Nike,125; Adidas 150" items_list = items.split(;) print(items_list) # Outputs ['New Balance,155', ' Nike,125', ' Adidas 150']
MAKING A COPY OF A LIST
In addition to copying through slicing, as we covered earlier, we can also use the built-in copy()
function.
list1 = [1, 2, 3] list2 = list1.copy() # Create a copy list2.append(4) # Modify the copy print(list1) # Remains unchanged and outputs [1,2,3] print(list2) # Outputs [1,2,3,4]
KEY THINGS TO REMEMBER
index()
method returns the index of the first occurrence of a desired element.append()
adds an item to the end of the list.extend()
adds all elements of a list to another list.insert()
inserts an item at a specified position in the list. It will not remove previous list elements as a result.remove()
removes the first occurrence of the specified item.pop()
Removes and returns an item at a specified position, defaulting to the last item if no index is specified.sort()
sorts the list items in ascending order by default. Can sort alphabetically for strings and numerically for integers. Sorting is case-sensitive, which affects the order when sorting strings.- We can use
reverse()
method and slicinglist[::-1]
to reverse lists. min()
returns the smallest item in a list,max()
returns the largest item,sum()
calculates the sum of the elements in a list with an option start value.split()
splits a string into a list of substrings based on a specified delimiter. The default delimiter is the whitespace within the string.copy()
creates a copy of the list to prevent modifications to the original list when changes are made to the copy.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |