A list is an ordered collection that can contain elements of any different type, including other lists.  Iteration on a list can be performed through a for-in loop.  Lists are mutable.

print([1, 'two', 3])

print([])

Specific items in a list can be retrieved using indexes:

list = [1,2,3,4]
first = list[0]

Range Function

The range function returns a list of integers.  range(4) returns a list from 0 to 3.

Concatenation

a = [1,2,3]
b = [4,5]
c = a + b
print(c)  
[1,2,3,4,5]

Slicing

The starting index is included the ending index is excluded

t = [2,4,6,8,10,12]

print(t[1:3])
[4,6]

print(t[:3])
[2,4,6]

print(t[3:])
[8,10,12]

Building a List

Use the list function to crate an empty list and the append method to add elements.  You can also create a list with empty brackets.

list = list()
list = []
list.append('book')
list.append(99)

print(list)
['book',99]

Operators

something = [1,2,3,4,5]

1 in something
True

15 in something
False

15 not in something
True

Sorting

myList.sort()

Functions for lists of numbers

  • len(list)
  • max(list)
  • min(list)
  • sum(list)

Split Function

str = 'this is a string'
list = str.split()

str = 'this-is-a-string' 
list = str.split('-')