Methods

Moving on to the last part of this chapter, we will study Methods. Methods are similar to functions, with just one exception. They are called upon values. This might be a bit difficult to understand at this point, but the given examples and explanations will help you with that. To give a gist of it, consider you have a list with 10 numbers. If you want to sort this list in an ascending order, you can use the sort() method "on the List values". This will return a sorted List.

Every data type has various methods related to them, and here we will study the ones related to Lists. These can be used to find, add, remove and manippulate values in a String.

Finding values in a List

In the last unit, we saw how to check if a value is present in a list or not. What if we want to find it's index? We could use the index() method for this cause.

>>> listExample = ['apple', 'berry', 'cherry', 'berry']
>>> listExample.index('berry')
1
>>> listExample.index('cherry')
2

As we can see, for values with a duplicate, the index of the first found value is printed.

>>> listExample = ['apple', 'berry', 'cherry', 'berry']
>>> listExample.index('blueberry')
ValueErrorTraceback (most recent call last)
<ipython-input-17-4cdab469cda8> in <module>()
      1 listExample = ['apple', 'berry', 'cherry', 'berry']
----> 2 listExample.index('blueberry')

ValueError: 'blueberry' is not in list

Python throws a ValueError if the value doesn't exist in the List.

Adding values in a List

Items can be added to a list using append() or insert() methods. These are fairly easy to understand, and do what they literally mean.

>>> listExample = ['apple', 'berry', 'cherry', 'berry']
>>> listExample.append('blueberry') # -> Using append()
>>> listExample
['apple', 'berry', 'cherry', 'berry', 'blueberry']
>>> listExample.insert(3, 'cherry')
>>> listExample
['apple', 'berry', 'cherry', 'cherry', berry', 'blueberry']

Notice the difference here, append() method adds a new item to the end of the List, whereas we can add a new item at any index using insert() method. You can use them at your own convenience for the task at hand.

TASK: Try using insert() and append() methods on a String. Observe the output!

Removing values from the List

This is something we have studied before, the remove() method. Do you recall? Don't worry if you don't. This is a very easy concept.

>>> listExample = ['apple', 'berry', 'cherry', 'berry']

In this example, having two 'berry' value looks quite annoying to the eye, doesn't it? Lets remove one! When we run the remove() method on it, which one do you think will be removed? It's the first instance of the value, similar to finding a value and getting back the index of the first instance.

>>> listExample = ['apple', 'berry', 'cherry', 'berry']
>>> listExample.remove('berry')
>>> listExample
['apple', 'cherry', 'berry']

See, it was that easy!

Sorting values in a List

There is a very easy way to sort a List in Python, which is really convenient when compared to other Programming languages. This can be done using the sort() method. To make it even better, this method can be used to sort a List of Strings using the alphabetical order as well.

>>> listExample = ['apple', 'berry', 'cherry', 'berry']
>>> listExample.sort()
>>> listExample
['apple', 'berry', 'berry', 'cherry']
>>> listExample = [1,2,5,6,7,2,3]
>>> listExample.sort()
>>> listExample
[1, 2, 2, 3, 5, 6, 7]

PRO TIP: While the default mode for sort is the ascending order, to make it into descending order, we can simply pass the argument reverse = True inside the sort() method. Example: listExample.sort(reverse = True). That would give you [7, 6, 5, 3, 2, 2, 1] as the output.

There are three important points you need to note while understanding sort():

  • You can't capture the sorted List in a variable while running the sort() method. It sorts the list in place.
  • Lists with both numerical and alphabetical values cannot be sorted together. It will throw a TypeError.
  • sort() uses the ASCII character base for the order of sorting. So, uppercase letters come before lowercase. For example, a lowercase 'd' will be after an uppercase 'E'.

PRO TIP: Use key = str.lower inside the sort() method to sort in alphabetical order.

results matching ""

    No results matching ""