Useful List Operations

strip(char)

The strip method is useful when you want to remove characters from the beginning and end of a string. When reading from a file you might find ‘\n’ the new line character, which helps the computer know when the next line will appear. .strip(‘\n’) will remove this character. .strip(” “) will also remove leading and trailing spaces for a string.

This method RETURNS a new string.

split(delim)

The split method is very useful. It will return a list of subtrings from a larger string.

long_string = "Hello, I would like to talk to the manager"

list_of_words = long_string.split(" ") # split at every space

print(list_of_words)

# this will print a list with each of the words in the original String

split(” , “) takes one argument which is the delimiter. If we provide the ” ” space character as the delimiter, then split() will return every element found in between spaces. You can also use a comma as the delimiter. Some files will use data split by commas instead of spaces.

In the example above, using split(” “), you can count the words in a string, or do different analysis of the data (a string in this case) with the resulting list. For example, you could loop through the list of words and check which one are longer than three characters.

insert()

my_list.insert(position, item)

Inserts an item at a given position. The insert() method contains two arguments. The first argument takes the position value where the new item will be inserted. The second argument takes the new item value.

append()

list.append (item)

This method takes the new value as an argument that will be inserted at the end of the list.

extend()

first_list.extend(second_list)

The extend() method is used to merge two list items and store the merged items in the first list.

This method takes the second list as the argument and adds the values of the second list at the end of the first list.

count()

list.count(item)

This method takes the item value as an argument that will be searched for in the list and returns the number of appearances of the item in the list as a numerical value. If the item value does not exist in the list, then it will return with the value 0.

index()

list.index(search_item)

This method takes the search item value as the argument, and returns the position value (index) of that item in the list, if it exists, otherwise, it generates a ValueError.

copy()

new_list = list.copy()

The copy() method is used to make a copy of a list. This method is useful for keeping original list values before modifying the list.

sort()

list.sort()

The sort() method is used to sort the elements of list. This method is useful when you are working with the same type of list data and you need to organize the data for any programming purpose.

clear()

list.clear()

The clear() method is used to remove all the items in a list and to empty lists. This method is useful for re-assigning the values of a list by removing the previous items.