Lists in PYTHON

Asked

Viewed 426 times

2

I’m using lists to do a little programming. Initially I wanted to make a program that created as many variables as the person wanted, but I found an easier way. I thought I’d create a list and add 10 elements to it. After that the program would have to read element by element to execute the next step of the program(I can’t reveal the next step), but I faced a problem, how to make the program read the separate lines of a list? For example:

Lista = [1, 2, 3, 4, 5]

My program would pick up item by item, in which case it would take the L-list item, the 1-item, and run the rest of the program, further forward it would take item 2 and run, continue until I reach 5. Is there a command that allows me to pick up the list item at the position I want and display it on the screen? Or that allows you to read line by line from the list? How to solve my problem? I’ve tried everything else!

2 answers

2

Use lista[0] to take the first element, lista[1] to pick up the second and so on. To know the size of a list use the function len().

lista = [1, 2, 3, 4, 5]

print(lista[0])
print(lista(1])
print(len(lista))

Another thing, in Python, avoid creating variables with the first character in uppercase, IE, use lista instead of Lista. The use of the first letter in upper case is reserved for the definition of the classes (Python does not complain but may generate some confusion).

2


You can try using the repeat loop for.

For example.

lista = [1, 2, 3, 4, 5]

for item in lista:
    print(item) # item é o número contido na lista que vc quer usar.

    #Aqui vc coloca o resto do programa

Translating: For each item in the list: it will print the (item)

or you can do so:

lista = [1, 2, 3, 4, 5]
n = len(lista)

for i in range(0, n):
    item = lista[i] # item é o número contido na lista que vc quer usar.
    print(item) 
    #Aqui vc coloca o resto do programa

It’s practically the same as the other, but in a less lean way.

Browser other questions tagged

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