How to use the contents of the index in Python?

Asked

Viewed 490 times

-2

I have a list "list()" with N indexes. I would like to know how I use the content of the index and save it in a variable. For example:

In index [1] is the word "dog"

How do I save the content of the index within a variable?

var = cow

My idea is to make the variable "floating" so that I can make a "for" and add the index + 1 so that I can store several values in the variable while running the program.

  • Try sharing your code so other people understand better what your question is

2 answers

1


To declare a list you must write:

MinhaLista = list()

To add an element to this list you must use the function append()

MinhaLista.append('vaca')
MinhaLista.append('cachorro')

>>MinhaLista
['vaca', 'cachorro']

Using a repeating structure such as the for you can add as many elements as you need to this list.

To access these items by index:

>>MinhaLista[0]
vaca

>>MinhaLista[1]
cachorro

You can also use the for to access the items in this list:

for animal in MinhaLista:
    print(animal)

vaca
cachorro

Having these indexes, you can change the item.

>>MinhaLista[1]
cachorro

MinhaLista[1] = 'passaro'

>>MinhaLista[1]
passaro

This playlist is recommended with several classes on lists. https://www.youtube.com/playlist?list=PLHz_AreHm4dlKP6QQCekuIPky1CiwmdI6

0

So it seems your problem can be solved as follows:

Lista = ["cachorro","vaca","gato"]
for palavra in Lista:
    temp = palavra
    #faça o que precisar com a variável temp

So regardless of the size of the list you will walk all over it. I put the temp not to be confused, but it is possible to work directly with palavra which became a temporary variable until the next loop iteration

Browser other questions tagged

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