Construindo com recursos nativos

Escrevendo código Python eficiente

Logan Thomas

Scientific Software Technical Trainer, Enthought

A Biblioteca Padrão do Python

  • Biblioteca Padrão do Python 3.6
    • Presente em toda instalação padrão do Python
  • Tipos nativos
    • list, tuple, set, dict e outros
  • Funções nativas
    • print(), len(), range(), round(), enumerate(), map(), zip() e outras
  • Módulos nativos
    • os, sys, itertools, collections, math e outros
Escrevendo código Python eficiente

Função nativa: range()

Digitando explicitamente uma lista de números

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Escrevendo código Python eficiente

Usando range() para criar a mesma lista

# 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]
Escrevendo código Python eficiente

Função nativa: range()

Usando range() com passo

even_nums = range(2, 11, 2)

even_nums_list = list(even_nums)
print(even_nums_list)
[2, 4, 6, 8, 10]
Escrevendo código Python eficiente

Função nativa: enumerate()

Cria uma lista indexada de objetos

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')]
Escrevendo código Python eficiente

Função nativa: enumerate()

Dá para definir um valor inicial

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')]
Escrevendo código Python eficiente

Função nativa: map()

Aplica uma função a um objeto

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]
Escrevendo código Python eficiente

Função nativa: map()

map() com lambda (função anônima)

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

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

print(list(sqrd_nums))
[1, 4, 9, 16, 25]
Escrevendo código Python eficiente

Vamos começar a usar os nativos!

Escrevendo código Python eficiente

Preparing Video For Download...