Monday, August 10, 2009

Python built in functions

Some built in functions in Python

Let's make a simple list of numbers

>>>numbers = [2,4,3,6,5]

To get the number of elements in numbers, we can use the len() method

>>>len(numbers)
5

To get the max element in the list we can use the max() method

>>>max(numbers)
6

The max() method is not restricted to lists of numbers only. It can work with any iterable.

Just like the max function returns the largest value from an iterable, the min() function returns the smallest value.

>>>min(numbers)
2

Suppose we have a String "Hello" and we want to create a list of the characters of the String, we can use the built-in list() function.

>>>list("Hello")
['H', 'e', 'l', 'l', 'o']

The list() function is not limited to String, we can give it any iterable and it will return a list of the elements of the iterable in the same order as they appear in the iterable.

If we want to delete an element in an iterable, we can use the del function
>>> hello_list = list("Hello")
>>> del hello_list[0]
>>> print hello_list
['e', 'l', 'l', 'o']

We can determine the type of an object using the type() function.
>>> type(hello_list)

No comments: