5.15 Other Sequence Processing Functions

Finding the Minimum and Maximum Values Using a Key Function

In [1]:
'Red' < 'orange'
Out[1]:
True
  • 'R' “comes after” 'o' in the alphabet, so you might expect 'Red' to be less than 'orange' and the condition above to be False.
  • Strings are compared by their characters’ underlying numerical values, and lowercase letters have higher numerical values than uppercase letters.
  • Confirm with built-in function ord:
In [2]:
ord('R')
Out[2]:
82
In [3]:
ord('o')
Out[3]:
111
In [4]:
colors = ['Red', 'orange', 'Yellow', 'green', 'Blue']
  • Assume that we’d like to determine the minimum and maximum strings using alphabetical order.
  • Can specify sort order with the key argument.
In [5]:
min(colors, key=lambda s: s.lower())
Out[5]:
'Blue'
In [6]:
max(colors, key=lambda s: s.lower())
Out[6]:
'Yellow'

Iterating Backwards Through a Sequence

In [7]:
numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
In [8]:
reversed_numbers = [item ** 2 for item in reversed(numbers)]
In [9]:
reversed_numbers
Out[9]:
[36, 25, 64, 4, 16, 81, 1, 49, 9, 100]

Combining Iterables into Tuples of Corresponding Elements

  • Built-in function zip enables you to iterate over multiple iterables of data at the same time.
  • Receives any number of iterables and returns an iterator that produces tuples containing the elements at the same index in each.
In [10]:
names = ['Bob', 'Sue', 'Amanda']
In [11]:
grade_point_averages = [3.5, 4.0, 3.75] 
In [12]:
for name, gpa in zip(names, grade_point_averages):
    print(f'Name={name}; GPA={gpa}')
Name=Bob; GPA=3.5
Name=Sue; GPA=4.0
Name=Amanda; GPA=3.75
  • Shortest argument determines the number of tuples produced.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.