Example 1: List

List is one of the built-in data types of Python, which is discussed in Activity 1.3.6 Tuples and Lists of the CSE course. We also discussed list in our Data Structure section (See http://www.pd4cs.org/data-structures-lists-and-tuples-in-python/ ).

We can use square brackets to create lists:

my_list = []
my_list = [1, 2, 3]

Because list is also a class, we can use its constructor to create lists:

# create an empty list
my_list = list() ##same as my_list = []

The constructor of list can take at most one argument, which should be an iterable, such as a tuple or a string.

## create the list [1, 2, 3]
my_list = list((1,2,3)) 

image001

## create the list ['a', 'b', 'c']
my_list = list('abc') 

image002

Use Instance Methods
There are several instance methods of list. When we created an instance of list, we can type “instance_name.” and press the Tab key to see all the methods of the instance.

image003

We can see that there are 9 instance methods. Let’s try several examples below.

# list.append(x) : Add an item to the end of the list
my_list = list('abc')
my_list.append('c')

image004

# list.count(x) : Return the number of times x appears in the list.
my_list.count('c')

image005

# list.reverse() : Reverse the elements of the list, in place.
my_list.reverse()

image006

**The story of Type and Class
If you input type(list) in Canopy, it will tell you list is a type rather than a class.

image007

This is a historical problem. In the olden days, there was a difference between user-defined classes and built in types. But since 2.2, there is no real difference. Essentially, a class is a mechanism Python gives us to create new user-defined types from Python code. The terms “class” and “type” are an example of two names referring to the same concept.

More information about list class see: https://docs.python.org/2.7/tutorial/datastructures.html?highlight=list