Sequence Data Types

  • Python supports a range of types to store sequences. Here we will explore lists, sets, tuples and dictionaries. The string type is also considered a sequence but for our purposes here we shall consider it as a simple list of characters.

  • A list is essentially an ordered collection of elements where the ordering is defined by the creator.

  • Lists are created using square brackets to enclose the sequence of elements

  • Elements can be added using the append() function

  • Access to a specific element is done again by the square bracket operator by providing the required index of the element. Note that in Python the first index is 0

  • Removing an element can be done by the del command or the .remove() function

  • Replacement is also done using the square-bracket operator

lottery_numbers = [1,2,3,4,5,6]

bonus = 7

# print the first element
# print the last element
lottery_numbers.remove(5) # Removes first occurrence of value 5 in list
del lottery_numbers[0]  # Removes the 0th element of the list

lottery_numbers[3] = 42

Givest the output:

[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 6, 7]
[2, 3, 4, 42, 7]
  • The square bracket operator also provides an operation known as slicing.

  • Slicing allows contiguous portions of lists to be sectioned out by using [i:j] syntax where i and j are indexes.

  • In this case it is helpful to think of the indices of the sequence slightly differently. Instead of thinking of each index as being assigned to a specific element within the list, think of them as being assigned to the boundaries of the elements, e.g.

  • The output of a slice operation is then much more obvious as it simple slices out the items within the boxes contained by the given range.

  • This also works with strings

my_list = ['M','A', 'N', 'T', 'I', 'D']

my_string = 'MANTID'

Gives the output:

['A', 'N', 'T']
  • Lists can be sorted using the sort() function which modifies the list in place.

my_list = [5,4,3,2,7]

Gives the output:

[5, 4, 3, 2, 7]
[2, 3, 4, 5, 7]
  • The default sorting criterion is less-than where items lower in the list are “less-than” items higher in the list. You can reverse this with,

l = [5,4,3,2,7]
print(l)  #prints list in descending order

Gives the output:

[7, 5, 4, 3, 2]

Category:Tested Examples