Redeem only 10 first Python object records

4

I'm curled up in a part of the code I'm doing. I need to retrieve only the first 10 records of an object that I call in a for loop:

listaTabela = []
        for aluno in alunos:
            listaLinha = ""
            listaLinha += str(aluno.getRA())
            listaLinha += ";"
            listaLinha += str(aluno.getNome())

            listaTabela.append(listaLinha)

The way it is, it makes the loop is usually as long as there are records in 'students'. Would there be a way to limit this loop so that it runs only in the first 10 records? I tried using while but he repeated the same record 10 times.

    
asked by anonymous 18.07.2018 / 16:39

3 answers

8

You can simply slice your list of students like this:

listaTabela = []

for aluno in alunos[:10]:
    listaLinha = ""
    listaLinha += str(aluno.getRA())
    listaLinha += ";"
    listaLinha += str(aluno.getNome())

    listaTabela.append(listaLinha)
    
18.07.2018 / 18:21
5

In your specific example, using the syntax indicated by @ThiagoLuizS is the best alternative. I just want to point out that not all iterable objects are "sliceable". For example, this can be iterated:

for i in map(int, '12345'):
    print(i)

But it can not be sliced:

map(int, '12345')[1:] # TypeError: 'map' object is not subscriptable

For these objects, use itertools.islice .

from itertools import islice
for i in islice(map(int, '12345'), 1, 5):
    print(i)
    
18.07.2018 / 21:48
2

If your Python is recent, try to use lists in understanding and f-strings:

tab=[f'Nome: {x.getNome()}; {x.getRA()}' for x in alunos[:10]]
    
18.07.2018 / 19:31