Lists

What are Lists?

Python lists are a versatile and common data types. You can store a sequence of elements (numbers, strings, or even other lists) in order and manipulate them easily.

Lists are defined with square brackets and the elements are separated by commas.

myList = [1 ,2, 3, 4]

You can also create an empty list by not putting any values between the square brackets. This is useful for when you need to create a list within a function; define an empty list beforehand and then sequentially add to it within the function.

emptyList = []

You can also use range() to create a range object. It takes up to three arguments and has the syntax of range(start, stop+1, step). Use list() to convert this range object into a list.

myList = list(range(1,11,1)) # Creates a list of numbers 1-10
myList = list(range(2,101,2)) # Creates a list of even numbers 2-100 

Accessing and Modifying List Elements

Lists are 0 index, meaning that the first item in the list has an index (position) of 0 and the last item has the index of 1 less than the length of the list. You can also count from the other end with negative numbers, with an index of -1 being the last item in the list. You can access the elements using the syntax:

myList[0]

And can update/overwrite the values like:

myList[0] = 1 # Overwrites the first item in the list (index 0) with a value of 1.

Using : you can select a segment of a list in the following ways.

myList[1:3]     # Gets elements at index 1 and 2
myList[:2]      # First two elements
myList[-2:]     # Last two elements
myList[:-1]     # All except the last
myList[:-n]     # All except the last 'n' values
myList[1:]      # All except the first
len(myList)	    # Returns the length of the list

Joining Lists

You can use + to join two or most lists together. This joining is known as concatenation.

newList = [1, 2] + [3, 4]  # [1, 2, 3, 4]

You can also zip() two lists together to create a two dimensional list (a list of lists). You can access the elements using listName[Index of outer list][Index of inner list].

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = list(zip(list1, list2))  # [(1, 'a'), (2, 'b'), (3, 'c')]

# Accessing 2D elements
print(zipped[0][1])  # Output: 'a'

Copying Lists

There are two ways of copying lists; using the .copy() list method or accessing a list passing : instead of indices.

list2 = myList[:]  # Makes a copy of myList
list3 = myList.copy()

Looping Through a List

One thing you can do with lists is loop through them and apply a function to each item in the list. The syntax for this is.

for i in myList:
    print(i)

for i in myList[0:3]:  # Loop through part of the list
    print(i)

A more succinct way of looping through a list is list comprehension. The general syntax for this is:

old_list = [values etc]
new_list = []

# Non-list comprehension
for temp_var in old_list:
	if conditional
		new_list.append(temp_var)

# List comprehension
new_list = [ temp_var for temp_var in old_list if conditional]

#The conditional isn't always required however.
squares = [x**2 for x in range(5)]	# Makes a list of the squares of the numbers 0-4 (0, 1, 4, 9, 16)

List Methods

The syntax for accessing list methods is list.method(input).

  • .append(): Adds an item to the end of a list.
  • .copy(): Return a copy of a list.
  • .extend(list): Add another list to the end of the first.
  • .index(x, start, end): Returns index of a value searched between index values.
  • .insert(i, x): Insert an item at a given index. i is the index to insert before.
  • .remove(): Removes a value from the list. It removes the first value it comes to that matches.
  • .clear(): Removes all items from the list.
  • .count(): Counts the number of occurrences of a given value in a list.
  • .insert(position, element): Inserts an element into a list at a certain position.
  • .pop(): Removes and returns the element at a specified index. If no index is given, it removes and returns the last item.
  • .sort() or sorted(list_name): Sorts a list. It can use an argument of reverse = True to make it back to front. You can also use a key. E.g. To sort by length of item in reverse order: .sort(key = len, reverse= True)
  • ",".join(list): Joins the list together into a string with "," between each entry.