Listas Python
Listas são um dos 4 tipos de dados em Python usados para armazenar coleções de dados.
# List: coleção ordenada de itens entre colchetes
['John', 'Peter', 'Debora', 'Charles']
Obtendo valores com índices
# Acessar elementos da lista usando índice (base 0, o primeiro elemento é o índice 0)
furniture = ['table', 'chair', 'rack', 'shelf']
furniture[0] # Retorna o primeiro elemento: 'table'
'table'
furniture[1]
'chair'
furniture[2]
'rack'
furniture[3]
'shelf'
Índices negativos
# Índice negativo: acessa elementos do final da lista
furniture = ['table', 'chair', 'rack', 'shelf']
furniture[-1] # Retorna o último elemento: 'shelf'
'shelf'
furniture[-3]
'chair'
f'The {furniture[-1]} is bigger than the {furniture[-3]}'
'The shelf is bigger than the chair'
Faça login para responder este quiz e acompanhar seu progresso de aprendizagem
furniture[-1] retorna se furniture = ['table', 'chair', 'rack', 'shelf']?'table''shelf'['shelf']IndexErrorObtendo sublistas com Slices (Fatiamento)
# Slicing: obter sublista usando a sintaxe [start:end] (end é exclusivo)
furniture = ['table', 'chair', 'rack', 'shelf']
furniture[0:4] # Retorna elementos do índice 0 ao 3 (4 excluído)
['table', 'chair', 'rack', 'shelf']
furniture[1:3]
['chair', 'rack']
furniture[0:-1]
['table', 'chair', 'rack']
# Slice do início: omita o índice de início (padrão é 0)
furniture[:2] # Retorna os dois primeiros elementos
['table', 'chair']
# Slice até o final: omita o índice final (padrão é o final da lista)
furniture[1:] # Retorna todos os elementos do índice 1 até o final
['chair', 'rack', 'shelf']
furniture[:]
['table', 'chair', 'rack', 'shelf']
O fatiamento da lista completa fará uma cópia:
# O fatiamento cria uma cópia: [:] cria uma cópia superficial da lista
spam = ['cat', 'bat', 'rat', 'elephant']
spam2 = spam[:] # Cria uma cópia, não uma referência
spam2
['cat', 'bat', 'rat', 'elephant']
spam.append('dog')
spam
['cat', 'bat', 'rat', 'elephant', 'dog']
spam2
['cat', 'bat', 'rat', 'elephant']
Faça login para responder este quiz e acompanhar seu progresso de aprendizagem
spam[:] cria quando spam é uma lista?Obtendo o comprimento de uma lista com len()
# len() retorna o número de itens em uma lista
furniture = ['table', 'chair', 'rack', 'shelf']
len(furniture) # Retorna 4
4
Alterando valores com índices
# Modificar elementos da lista atribuindo novos valores aos índices
furniture = ['table', 'chair', 'rack', 'shelf']
furniture[0] = 'desk' # Substitui o primeiro elemento
furniture
['desk', 'chair', 'rack', 'shelf']
furniture[2] = furniture[1]
furniture
['desk', 'chair', 'chair', 'shelf']
furniture[-1] = 'bed'
furniture
['desk', 'chair', 'chair', 'bed']
Concatenação e Replicação
# Concatenação de listas: combina duas listas usando o operador +
[1, 2, 3] + ['A', 'B', 'C'] # Retorna [1, 2, 3, 'A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
# Replicação de lista: repete a lista várias vezes usando o operador *
['X', 'Y', 'Z'] * 3 # Retorna ['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
my_list = [1, 2, 3]
my_list = my_list + ['A', 'B', 'C']
my_list
[1, 2, 3, 'A', 'B', 'C']
Usando loops for com Listas
# Iterar sobre os elementos da lista usando loop for
furniture = ['table', 'chair', 'rack', 'shelf']
for item in furniture: # Percorre cada item
print(item)
table
chair
rack
shelf
Obtendo o índice em um loop com enumerate()
# enumerate() retorna tanto o índice quanto o valor em um loop
furniture = ['table', 'chair', 'rack', 'shelf']
for index, item in enumerate(furniture): # Obtém índice e item juntos
print(f'index: {index} - item: {item}')
index: 0 - item: table
index: 1 - item: chair
index: 2 - item: rack
index: 3 - item: shelf
Loop em Múltiplas Listas com zip()
# zip() combina múltiplas listas elemento por elemento em um loop
furniture = ['table', 'chair', 'rack', 'shelf']
price = [100, 50, 80, 40]
for item, amount in zip(furniture, price): # Emparelha elementos de ambas as listas
print(f'The {item} costs ${amount}')
The table costs $100
The chair costs $50
The rack costs $80
The shelf costs $40
Os operadores in e not in
# Operador in: verifica se um item existe em uma lista
'rack' in ['table', 'chair', 'rack', 'shelf'] # Retorna True
True
'bed' in ['table', 'chair', 'rack', 'shelf']
False
furniture = ['table', 'chair', 'rack', 'shelf']
'bed' not in furniture
True
'rack' not in furniture
False
O Truque da Atribuição Múltipla
O truque da atribuição múltipla é um atalho que permite atribuir múltiplas variáveis com os valores em uma lista em uma única linha de código. Então, em vez de fazer isto:
furniture = ['table', 'chair', 'rack', 'shelf']
table = furniture[0]
chair = furniture[1]
rack = furniture[2]
shelf = furniture[3]
Você poderia digitar esta linha de código:
furniture = ['table', 'chair', 'rack', 'shelf']
table, chair, rack, shelf = furniture
table
'table'
chair
'chair'
rack
'rack'
shelf
'shelf'
O truque da atribuição múltipla também pode ser usado para trocar os valores em duas variáveis:
a, b = 'table', 'chair'
a, b = b, a
print(a)
chair
print(b)
table
O Método index
O método index permite encontrar o índice de um valor passando seu nome:
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.index('chair')
1
Adicionando Valores
append()
append adiciona um elemento ao final de uma list:
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.append('bed')
furniture
['table', 'chair', 'rack', 'shelf', 'bed']
Faça login para responder este quiz e acompanhar seu progresso de aprendizagem
append() faz com uma lista?insert()
insert adiciona um elemento a uma list em uma posição dada:
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.insert(1, 'bed')
furniture
['table', 'bed', 'chair', 'rack', 'shelf']
Removendo Valores
del
del remove um item usando o índice:
furniture = ['table', 'chair', 'rack', 'shelf']
del furniture[2]
furniture
['table', 'chair', 'shelf']
del furniture[2]
furniture
['table', 'chair']
remove()
remove remove um item usando seu valor real:
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.remove('chair')
furniture
['table', 'rack', 'shelf']
Removendo itens repetidos
Se o valor aparecer múltiplas vezes na lista, apenas a primeira ocorrência do valor será removida.
pop()
Por padrão, pop removerá e retornará o último item da lista. Você também pode passar o índice do elemento como um parâmetro opcional:
animals = ['cat', 'bat', 'rat', 'elephant']
animals.pop()
'elephant'
animals
['cat', 'bat', 'rat']
animals.pop(0)
'cat'
animals
['bat', 'rat']
Faça login para responder este quiz e acompanhar seu progresso de aprendizagem
pop() faz quando chamado em uma lista?Ordenando valores com sort()
numbers = [2, 5, 3.14, 1, -7]
numbers.sort()
numbers
[-7, 1, 2, 3.14, 5]
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.sort()
furniture
['chair', 'rack', 'shelf', 'table']
Você também pode passar True para o argumento de palavra-chave reverse para fazer com que sort() ordene os valores em ordem inversa:
furniture.sort(reverse=True)
furniture
['table', 'shelf', 'rack', 'chair']
Se você precisar ordenar os valores em ordem alfabética regular, passe str.lower para o argumento de palavra-chave key na chamada do método sort():
letters = ['a', 'z', 'A', 'Z']
letters.sort(key=str.lower)
letters
['a', 'A', 'z', 'Z']
Você pode usar a função embutida sorted para retornar uma nova lista:
furniture = ['table', 'chair', 'rack', 'shelf']
sorted(furniture)
['chair', 'rack', 'shelf', 'table']
O tipo de dado Tuple
A principal diferença entre tuplas e listas é que, enquanto as tuplas são objetos imutáveis, as listas são mutáveis. Isso significa que tuplas não podem ser alteradas enquanto as listas podem ser modificadas. Tuplas são mais eficientes em termos de memória do que as listas.
furniture = ('table', 'chair', 'rack', 'shelf')
furniture[0]
'table'
furniture[1:3]
('chair', 'rack')
len(furniture)
4
A principal forma como as tuplas diferem das listas é que as tuplas, como as strings, são imutáveis.
Convertendo entre list() e tuple()
tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
list(('cat', 'dog', 5))
['cat', 'dog', 5]
list('hello')
['h', 'e', 'l', 'l', 'o']
Faça login para responder este quiz e acompanhar seu progresso de aprendizagem