How to make a replacement using the tuple list in python

Asked

Viewed 94 times

-2

The question asks for :

A buffet restaurant offers only five basic types of food. Think of five simple dishes and store them in a tuple. • Use a for loop to display each dish offered by the restaurant. • Try modifying one of the items and check that Python rejects the change. • The restaurant changes its menu, replacing two of the items with dishes different. Add a code block that rewrites the tuple and then use a for loop to display each of the revised menu items.


for comida in buffet : 
    print (comida)```


Mas eu não estou conseguindo fazer a substituição 

eu já tentei ```buffet[0,1] =( "jaca" , "angu" )
                buffet(0,1) =( "jaca" , "angu" )
                buffet = ( "jaca" , "angu" )```

As duas primeiras dão erro , a ultima substituiria toda a lista 

2 answers

1


The purpose of this exercise is to compare the characteristic of imutabilidade of primitive types list and tuples in Python.

Just look at a possible step-by-step solution:

# Um restaurante do tipo buffet oferece
# apenas cinco tipos básicos de comida.
# Pense em cinco pratos simples e
# armazene-os em uma tupla.

cardapio = ('arroz','feijao','batata','salada','farofa')

# Use um laço for para exibir cada
# prato oferecido pelo restaurante

for prato in cardapio:
    print(prato)

# Tente modificar um dos itens e cerifique-se
# de que Python rejeita a mudança.

try:
    cardapio[0] = 'pizza'
except TypeError:
    print('Tuplas sao imutaveis!')

# O restaurante muda seu cardápio, substituindo
# dois dos itens com pratos diferentes. Acrescente
# um bloco de código que reescreva a tupla

cardapio = list(cardapio)  # Converte Tupla Para Lista
cardapio[0] = 'jaca'       # Altera o primeiro prato do cardapio
cardapio[1] = 'angu'       # Altera o segundo prato do cardapio
cardapio = tuple(cardapio) # Reescreva a tupla

# Em seguida, use um laço for para exibir cada
# um dos itens do cardápio revisado.

for prato in cardapio:
    print(prato)

Exit:

arroz
feijao
batata
salada
farofa
Tuplas sao imutaveis!
jaca
angu
batata
salada
farofa

See working on Repl.it

  • Thank you very much !!

1

The tuple has the premise of being immutable, what does that mean? You are able to see what is in each position of the tuple but you are not able to change it. Tuples resemble strings. Whenever you try to change the contents of a tuple the interpreter will accuse an error, realize that, you can not change the contents of a tuple but can, with the same variable, receive another tuple.

The list data structure is mutable, so you should convert the tuple to list, add new content and return to tuple.

a = ('a', 'b', 'c', 'd', 'e')
for i in a:
    print(i)

print()

aux = list(a)
aux[0] = 1
aux[1] = 'biscoito'
a = tuple(aux)

for i in a:
    print(i)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.