Using Python Lists - Tutorial with Examples

Python lists basics

List in Python is a sequence of elements.

List elements, or items, are written between square brackets. They are separated by comma.

Python List elements does not have to be of the same type.

It is perfectly OK to have lists like this:

 L = [7.9, "Hi", True, 2]  

Let's quick check what type are list L elements using type() function like this:

 for i in L:  

Result is:

 <class 'float'>  
 <class 'int'>  
 <class 'bool'>  
 <class 'str'>  

As you can see you can have float, integer, boolean and string, all in one list.

Python list elements have position or index which is a number greater or equal to zero.

List L element 7.9 has index 0 (zero). Element "Hi" has index 1. Element True has index 2. Element 2 has index 3.

If you want to print elements of the list along with their type add next line inside for loop:


The result is:

 <class 'float'>  
 <class 'str'>  
 <class 'bool'>  
 <class 'int'>  

Function len()

Function len() is used when you want to find out how many elements list holds.

 print("List L has "+str(len(t))+" elements")  

Run this script and you will get message: List L has 4 elements.

We are using string concatenation within print command and str() function converts integer into string.

Python Lists Slicing

Slicing [start:end] means everything between start and end, including start but not end.
When start is omitted it means from beginning of list. When end is omitted it means until end of list.

lst = [2, 14, 89, 33, 7, 43]

print("lst = [2, 14, 89, 33, 7, 43]")

print(lst[:]) -> [2, 14, 89, 33, 7, 43]
print(lst[3:]) -> [33, 7, 43]
print(lst[:4]) -> [2, 14, 89, 33]
print(lst[3:5]) -> [33, 7]

Python min and max functions

Find maximum and minimum numbers from list 66, 72, 12, 90, 43.

While this is very easy task for humans, you can tell the result right away, there are situations where you need to write a program to find the solution. Let's say numbers are not predefined but entered by user or returned from some function or calculation or you have very large collection of numbers, you will not spend 2 hours to look for min and max, right?

If you have your numbers in a list, finding min and max is straightforward:

 L = [66, 72, 12, 90, 43]  

If you know that sort() function sorts any list in ascending order and reverse() function reverses the list in place, how would you find largest and smallest element of the list without using max and min functions?

Very easy:
 L = [66, 72, 12, 90, 43]  


Post a Comment