Python Lists and Tuples

Lists are one of the most common types of collections in Python. They can be recognized by square brackets that surround a series of values. The values can be numbers, strings, objects, or even other lists.

names = ['Toad', 'Badger', 'Ratty', 'Mole', 'Mole']
ages = [28, 56, 34, 23, 23]
empty = [] # creates an empty list
assorted = ['Kenneth', 89, ['The Wind in the Willows', 'The Reluctant Dragon']]

The element inside lists are ordered, which allows them to be indexed. Each list element can be accessed individually by its index number. For example, names[1] will return the second element as lists begin at index 0.

List elements can also be accessed by negative indexing. To access the last element of a list, use list_name[-1]. To access the second to last element, use list_name[-2].

An error is created if you attempt to access an index that does not exist.

test_scores = [67,85,94,78,89]
test_scores[0] # returns 67
test_scores[-1] # returns 89
test_scores[99] # returns an IndexError

A range of list elements can be accessed with slicing. Slicing a list uses two index numbers separated by a colon to mark the beginning and ending of the slice. For instance, list_name[1:6].

The slice range is not inclusive. The slice list_name[1:3] would only include the values at index 1 and 2.

test_scores = [67,85,94,78,89]
test_scores[1:3] # returns [85,94]

Slicing creates a new list. If you are assigning the result of a slice to a new variable, and modify that variable, the original list remains unchanged.

Python includes a len() function that returns a count of how many items are in a list.

list1 = ['one', 'two', 'three']
list2 = [1]

len(list1) # returns 3
len(list2) # returns 1

List Methods

Lists have several built-in methods that can be used to perform operations on the list.

The append() method adds items to the end of the list.

list1 = ['one', 'two', 'three']
list1.append('four')
print(list1)  # prints ['one', 'two', 'three', 'four']

The insert() method inserts a new item at the specified index. It does not remove any existing items.

list1 = ['one', 'two', 'three']
list1.insert(0, 'zero')
print(list1)  # prints ['zero', 'one', 'two', 'three']

The index() method returns the index of the specified value. A ValueError is returned if the element does not exist.

list1 = ['one', 'two', 'three']
print(list1.index('two'))  # prints 1
print(list1.index('ten'))  # returns a ValueError

The extend() method combines a list with the elements of another list. It also works any iterable such as tuples, strings, ranges, etc.

list1 = ['one', 'two', 'three']
list2 = ['four', 'five']
list1.extend(list2)
print(list1)
list1.extend(range(5))
print(list1)

The remove() method removes the specified item from the list. A ValueError is returned if the element does not exist.

list1 = ['one', 'two', 'three']
list1.remove('three')
print(list1)  # prints ['one','two']

The count() method returns the number of times an item appears in the list.

list1 = ['one', 'two', 'three', 'one']
print(list1.count('one'))  # prints 2

The pop() method removes the item at the given index and returns the value. An IndexError occurs if you try to pop an element from an empty list.

list1 = ['one', 'two', 'three']
value = list1.pop(0)
print(value)  # prints 'one'

The reverse() method reverses the list.

list1 = ['one', 'two', 'three']
list1.reverse()
print(list1)

The sort() method will sort items in the list in ascending or descending order. Set the reverse parameter to True to reverse sort, sort(reverse=True).

list1 = [5,4,3,6,1,2]
list1.sort()
print(list1)

The copy() method will copy a list into a new variable. This method is needed when you want to work with a second copy of the list. Changes made to the second list do not affect the original list.

list1 = ['one', 'two', 'three']
list2 = list1
list2.append('four')
print(list1)

list1 = ['one', 'two', 'three']
list2 = list1.copy()
list2.append('four')
print(list1)

The clear() method removes all the elements from a list.

list1 = ['one', 'two', 'three']
list1.clear()
print(list1)  # prints []

The Sorted Function

sorted() is a built-in Python function that sorts the specified iterable object passed into it. Strings are sorted alphabetically and numbers are sorted numerically. You can sort by ascending or descending order. You cannot sort lists that contain both strings and numbers.

list1 = [5,4,6,2,1]
print(sorted(list1)) 	 # prints [1,2,4,5,6]
print(sorted('Coffee'))  # prints ['C', 'e', 'e', 'f', 'f', 'o']

del Keyword

The del keyword in Python deletes objects such as strings, variables, and Class instances. It can also be used to delete elements in a list.

list1 = ['one', 'two', 'three']
del list1[2]
print(list1) # prints ['one','two']

List Iteration

You can iterate over the elements in a list by using a for loop.

For loops will provide the values in a list but not the index numbers. Use the range() and len() functions to generate sequence of numbers to serve as that list’s indices.

list1 = ['one', 'two', 'three']
for item in list1:
	print(item)

for i in range(len(list1)):
	print(i, ":", list1[i])

In and Not In

An if-statement can easily check whether a list contains a certain value using the in keyword.

Likewise, the not keyword can be added to check if a list does not contain the value.

list1 = [1,2,3,4,5]
if 1 in list1:
	print('The list contains 1')
else:
	print('The list does not contain 1')

if 6 not in list1:
	print('The list does not contain 6')

List Comprehensions

List comprehension is a shorter syntax for creating and generating lists than using a for loop. The general syntax for this is:

new_list = [expression for item in iterable if condition == True]

# generate a list of numbers from 0-99
numbers = [x for x in range(100)]

# generate a list of even numbers from 0-99
evens = [x for x in range(100) if x % 2 == 0]

# generate a new list from another list of words
# that contain the letter 'e', then capitalize the value
list1 = ['one', 'two', 'three', 'four', 'five']
list2 = [s.upper() for s in list1 if 'e' in s]
print(list2)

Copying and Cloning

Lists in Python do not contain the values themselves but a reference to the place in memory where the values are stored. You cannot copy a list as simply as list1 = list2. If we did, changes made in one list would affect both lists since both variable names are pointing to the same place in memory.

However, there are two ways to copy lists in Python, the copy() method and list slicing.

list1 = ['one', 'two', 'three', 'four', 'five']
list2 = list1.copy()
list3 = list1[:]

list2[0] = 'six'
list3[0] = 'seven'

print(list1)  # prints ['one', 'two', 'three', 'four', 'five']
print(list2)  # prints ['six', 'two', 'three', 'four', 'five']
print(list3)  # prints ['seven', 'two', 'three', 'four', 'five']

Tuples

A tuple is another data structure in Python. They are very similar to lists but with the exception of not being mutable. You cannot add or remove items once the tuple is created. Tuples are recognized by comma-separated values surround by parentheses.

tuple1 = 1,
tuple2 = (1,)
tuple3 = (1,2,3)

# create new tuple by adding elements from other tuples
tuple4 = tuple1 + tuple2 + tuple3

for item in tuple4:
	print(item)

Like lists, the elements of a tuple can be accessed by index or slicing. Tuple indexes start at 0. And you can check if items exist using the if-in statement.

tuple1 = (1,2,3,4,5,6)
print(tuple1[0])    # prints 1
print(tuple1[1:3])  # prints (2,3)

if 4 in tuple1:
	print('The value 4 exists in the tuple')

Modifying Tuples

You cannot modify elements in a tuple. However, you can convert a tuple to a list, modify the list, and then convert the list into a tuple. This process creates a new tuple that shares no relationship with the original.

tuple1 = (1,2,3,4,5,6)
list1 = list(tuple1)
list1.append(7)
tuple1 = tuple(list1)
print(tuple1)

The important thing to understand is that tuples cannot be modified. Consider a different data structure if you find yourself needing to modify tuples.

Lists Inside Tuples

Tuples can contain any object, just like lists. They can even contain lists and other tuples.

tuple1 = (1, (2,3), [4,5,6])
print(tuple1[2])

Lists Versus Tuples

The main difference between lists and tuples is that lists are mutable and tuples are not. Apart from that, there are a few different use cases where a tuple may be preferred.

  1. Tuples help developers identify data that should not be changed during the program execution
  2. Tuples can be used as keys in dictionaries whereas lists cannot
  3. Tuples have an slight edge in performance over lists