Considere-se a lista seguinte, assim como algumas operações de consulta da lista.
>>> myList = ["The", "earth", "revolves", "around", "sun"] >>> myList ['The', 'earth', 'revolves', 'around', 'sun'] >>> myList[0] 'The' >>> myList[4] 'sun' >>> myList[5] Traceback (most recent call last): File "", line 1, in IndexError: list index out of range
Um índice negativo consulta a lista a partir da extremidade final
>>> myList[-1] 'sun'
Podem inserir-se elementos em posições determinadas.
>>> myList.insert(0,"Yes") >>> myList ['Yes', 'The', 'earth', 'revolves', 'around', 'sun']
Para adicionar elementos à lista, é possível usar a função append ou a função extend. A primeira adiciona apenas um elemento. A segunda, se o elemento for uma lista, estende-a com os elementos dessa lista.
>>> myList.append(["a", "true"]) >>> myList ['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true']] >>> len(myList) 7
>>> myList.extend(["statement", "for", "sure"]) >>> myList ['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure'] >>> len(myList) 10
Podem extrair-se elementos de uma lista com a função slice.
>>> myList[1:4] ['The', 'earth', 'revolves'] >>> myList[:4] ['Yes', 'The', 'earth', 'revolves'] >>> myList[4:] ['around', 'sun', ['a', 'true'], 'statement', 'for', 'sure'] >>> myList[:] ['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
Pesquisa em listas a partir do conteúdo:
>>> myList.index("revolves") 3 >>> myList.index("a") Traceback (most recent call last): File "", line 1, in ValueError: 'a' is not in list >>> myList.index(["a", "true"]) 6 >>> "sun" in myList True
Remover elementos:
>>> myList ['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure'] >>> myList.remove("Yes") >>> myList ['The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure'] >>> myList.remove("statement") >>> myList ['The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'for', 'sure'] >>> myList.remove(["a", "true"]) >>> myList ['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure'] >>> myList.pop() 'sure' >>> myList ['The', 'earth', 'revolves', 'around', 'sun', 'for']
Operadores de listas
>>> myList ['The', 'earth', 'revolves', 'around', 'sun', 'for'] >>> myList = myList + ["sure"] >>> myList ['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure'] >>> myList += ["."] >>> myList ['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.'] >>> myList *= 2 >>> myList ['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.', 'The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.']