Acessar tuplas em Python

Vamos aprender o acesso a tuplas do Python com exemplos neste artigo, na esperança de que seja útil para a educação.

Itens de tuplas de acesso do Python

Ao trabalhar com tuplas de acesso Python , você pode acessar itens de tupla por seu número de índice, entre colchetes [] :

Na tupla, imprima o quarto item:

Example: 

1
2
3
4
5
6
country_tuple = ("United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy")
print(country_tuple[3])
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Lembrete: É importante observar que o primeiro item possui índice 0 .



Intervalo de índices

As tuplas de acesso do Python permitem que você defina um ponto inicial e um ponto final para um intervalo de índices.

A tupla retornada contém todos os itens no intervalo especificado se o intervalo for definido.

O quarto, quinto e sexto itens devem ser devolvidos da seguinte forma:

Example: 

1
2
3
4
5
6
country_tuple = ("United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy")
print(country_tuple[3:6])
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Lembrete: Vale ressaltar que a busca começará no índice 3 (incluso) e terminará no índice 6 (não incluído).

Você deve se lembrar que o índice do primeiro item é 0.

Na ausência de um valor inicial, o intervalo começará no primeiro item da lista.

Neste exemplo, os itens são retornados desde o início, mas não incluindo, “Espanha”:

Example: 

1
2
3
4
5
6
7
8
9
country_tuple = ("United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy")
print(country_tuple[:5])
#The items from index 0 to index 5 will be returned by this method.
#Remember that index 0 represents the first item, and index 5 represents the sixth item.
#It is important to remember that the item in index 5 is not included.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Se o intervalo não contiver um valor no final, ele irá para o final da lista.

Neste exemplo, retornamos os itens de “Brasil” ao final:

Example: 

1
2
3
4
5
6
7
8
country_tuple = ("United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy")
print(country_tuple[3:])
#This will return the items from index 3 to the end of the list.
#It is important to remember that index 0 is the first item, and index 1 is the second item.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Indexação negativa

A indexação negativa das tuplas de acesso do Python significa começar do final.

  • O último item é numerado -1,
  • O -2 indica o penúltimo item, etc.

Pegue o último item da tupla e imprima-o:

Example: 

1
2
3
4
5
6
country_tuple = ("United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy")
print(country_tuple[-1])
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Verifique se o item existe

Se estivermos falando sobre tuplas de acesso do Python , podemos usar a palavra-chave in para verificar se um item existe.

Verifique se “Alemanha” aparece na lista:

Example: 

1
2
3
4
5
6
7
country_tuple = ("United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy")
if "Germany" in country_tuple:
print("Yes, 'Germany' is in the Country tuple")
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Gama de Índices Negativos

Em tuplas de acesso do Python , especifique índices negativos se quiser começar a pesquisar a partir do final.

Usando este exemplo, retornamos todos os itens de “Brasil” (-7) para, mas excluímos “Itália” (-1):

Example: 

1
2
3
4
5
6
7
8
9
country_tuple = ("United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy")
print(country_tuple[-7:-1])
#The term "negative indexing" refers to starting at the end of the list.
#The following example returns items from index -7 (included) to index -1 (excluded).
#Keep in mind that the last item has an index of -1.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Compartilhe seus pensamentos e ajude-nos a melhorar! Deixe sua reação abaixo para apreciar nossos esforços ou fornecer sugestões para este site.
Nós valorizamos o seu feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Assine a nossa newsletter
Digite seu e-mail para receber um resumo semanal de nossos melhores posts. Saber mais!
ícone