Building with built-ins

Writing Efficient Python Code

Logan Thomas

Scientific Software Technical Trainer, Enthought

The Python Standard Library

  • Python 3.6 Standard Library
    • Part of every standard Python installation
  • Built-in types
    • list, tuple, set, dict, and others
  • Built-in functions
    • print(), len(), range(), round(), enumerate(), map(), zip(), and others
  • Built-in modules
    • os, sys, itertools, collections, math, and others
Writing Efficient Python Code

Built-in function: range()

Explicitly typing a list of numbers

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Writing Efficient Python Code

Using range() to create the same list

# range(start,stop)
nums = range(0,11)

nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# range(stop)
nums = range(11)

nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Writing Efficient Python Code

Built-in function: range()

Using range() with a step value

even_nums = range(2, 11, 2)

even_nums_list = list(even_nums)
print(even_nums_list)
[2, 4, 6, 8, 10]
Writing Efficient Python Code

Built-in function: enumerate()

Creates an indexed list of objects

letters = ['a', 'b', 'c', 'd' ]

indexed_letters = enumerate(letters)

indexed_letters_list = list(indexed_letters)
print(indexed_letters_list)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Writing Efficient Python Code

Built-in function: enumerate()

Can specify a start value

letters = ['a', 'b', 'c', 'd' ]

indexed_letters2 = enumerate(letters, start=5)

indexed_letters2_list = list(indexed_letters2)
print(indexed_letters2_list)
[(5, 'a'), (6, 'b'), (7, 'c'), (8, 'd')]
Writing Efficient Python Code

Built-in function: map()

Applies a function over an object

nums = [1.5, 2.3, 3.4, 4.6, 5.0]

rnd_nums = map(round, nums)

print(list(rnd_nums))
[2, 2, 3, 5, 5]
Writing Efficient Python Code

Built-in function: map()

map() with lambda (anonymous function)

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

sqrd_nums = map(lambda x: x ** 2, nums)

print(list(sqrd_nums))
[1, 4, 9, 16, 25]
Writing Efficient Python Code

Let's start building with built-ins!

Writing Efficient Python Code

Preparing Video For Download...