Lists are similar to C array types.  A list can accept any Python object, including other lists.

You can create a list in several ways:

a = list()    # creates an empty list (a)

a = [ ]        # using brackets to create an empty list (a)

a = [1,2,3,4,5]    # creates a list of integers 1-5

a = [1, ‘SQL’, 3.45, [1,2,3] ]    # Creates a list of various data types: integer, string, float, and another list

a = [ (1,2), (101,102) ]    # Creates a list of Tuples (later)

a = [ {‘City’: ‘Seattle’, ‘State’: ‘Washington’, ‘Population’: ‘2.3M’} ]   # Creates a list of Dictionaries (later)

Range:

You can create a list of integers using the range() function:

x = list(range(9))

x = list(range(1,10))

x = list(range(1,10,2))   # 1-10, by 2 (called the ‘step’)

prints:

[1, 2, 3, 4, 5, 6, 7, 8][1, 2, 3, 4, 5, 6, 7, 8, 9][1, 3, 5, 7, 9]   # note: all odd values

 

 

You can convert another object to a list:

x = ‘this is a string’

y = list(x)

Python lists keep insertion order, that is, when you access the list contents, they will be in the order they

were inserted.  There are other collections that do not follow this functionality.

You can print the list:

Python 3.x:

print(a)

Python 2.x:

print a

List are mutable, that is, you can change them after creation.

Append to the end of a list:

a.append(‘Server’)

Insert to a specific location within the list:

list_name.insert(index, value)

a.insert(2, ‘Server’)

Clear the list of all it’s contents:

a.clear()

You can also just overwrite the list content:

a = 1,2,3,4,5

a = ‘Python is Cool!’

One often desirable function to perform on lists is to sort them:

a = [1,2,33,5,7,22,101,3]

a.sort()

print(a)

prints:

[1, 2, 3, 5, 7, 22, 33, 101]

This is an in-place sort, meaning it does not return a sorted list, it sorts the existing list values.

The sorted() function returns a new sorted list:

old = [1, -1, 22, 6]

print(old)

new = sorted(old)

print(new)

prints:

[1, -1, 22, 6][-1, 1, 6, 22]

 


 

References:

Python Website:  www.python.org

Python lists:  list_URL