How to access a list that is inside another list in Python?

Asked

Viewed 97 times

2

I have a list that has within it another list with the students' names, and a list that has been divided into two more lists, representing the first note and the second note. For example:

[['Matheus', 'Julia', 'Eduardo'], [[9.4, 4.7, 3.2], [7.2, 8.3, 2.4]]]

I would like to know what I do to access each level of this list, to separately return the students' names, their first grade and second grade. I tried it this way:

nome = []
nota1 = []
nota2 = []

for i in range(0, 3):
   nome.append(str(input('Nome do Aluno: ')))
   nota1.append(float(input('Nota 1: ')))
   nota2.append(float(input('Nota 2: ')))
   print('\n')

notas = []
notas.append(nota1)
notas.append(nota2)

listaAlunos = []
listaAlunos.append(nome)
listaAlunos.append(notas)

for i in range(0, len(listaAlunos)):
   for j in range(0, 3):
      print(listaAlunos[i][j])

2 answers

1

You could otherwise store as dictionary for example, but follows a possible answer to list within list:

for i, aluno in enumerate(listaAlunos[0]):
    print(aluno)
    print(f'nota 1 - {listaAlunos[1][0][i]}')
    print(f'nota 2 - {listaAlunos[1][1][i]}') 

The enumerate generates a 'counter' and we can use as index in the vector.

Entree:

Nome do Aluno: maria
Nota 1: 10
Nota 2: 20

Nome do Aluno: josé
Nota 1: 23
Nota 2: 24

Nome do Aluno: moises
Nota 1: 23
Nota 2: 45

Nome do Aluno: matusalem
Nota 1: 34
Nota 2: 45

Exit:

maria
nota 1 - 10.0
nota 2 - 20.0
josé
nota 1 - 23.0
nota 2 - 24.0
moises
nota 1 - 23.0
nota 2 - 45.0
matusalem
nota 1 - 34.0
nota 2 - 45.0
  • I have not studied the dictionaries part, and in this exercise the teacher wants to use the knowledge of lists within lists.

  • Could you explain to me why you put inside the enumarate listAlunos[0]?

  • You used listAlunos[0] in the enumarate because the amount of index already serves the other elements?

  • Hello Matheus, good afternoon! I have listed Students[0] because this is the student’s entry in your list. Making a listAlunos[0] I have the students' names, and so I can iterate on them. Already listAlunos[1][0] I have the first notes and listAlunos[1][1] we have the second note, we move by the data using the Dice i. Hug!

  • 1

    Got it, thanks a lot for the help man! You have no idea how I can understand this problem and the others I was trying to solve.

  • For nothing, anything we are there! Hug!

  • Since you should only use lists, think of a structure similar to the list of dictionaries. Use, for example: [ ['Matheus", 9.4, 7.2 ], ["Julia", 4.7 , 8.3], ..... ] . This structure is more clean since the data of the objects (students) are contained in a structure and not scattered. This will also help with data recovery and you can use the filter as described.

Show 2 more comments

1


There are better ways to store your data as a list of dictionaries, or namedtuple lists. If the student model were more complex, it would still have the list of classes defined by the programmer.

But first...

Answering the question

listaAlunos = [['Matheus', 'Julia', 'Eduardo'], [[9.4, 4.7, 3.2], [7.2, 8.3, 2.4]]]

alunos, notas = listaAlunos

for i in range(len(alunos)):
    print(f"Aluno: {alunos[i]}")
    for n, notaAluno in enumerate(notas):
        print(f"Nota {n+1}: {notaAluno[i]}")

Other options

List of dictionaries

The form of storage would be

listaAlunos = []

for i in range(0, 3):
   nome = input('Nome do Aluno: ')
   nota1 = float(input('Nota 1: '))
   nota2 = float(input('Nota 2: '))
   listaAlunos.append({"aluno": nome, "nota1": nota1, "nota2": nota2})
   print('\n')

We would have as value

[{'aluno': 'Matheus', 'nota1': 9.4, 'nota2': 7.2}, 
 {'aluno': 'Julia', 'nota1': 4.7, 'nota2': 8.3}, 
 {'aluno': 'Eduardo', 'nota1': 3.2, 'nota2': 2.4}
]

To print

for aluno in listaAlunos:
    print(f"Aluno: {aluno['aluno']}")
    print(f"Nota 1: {aluno['nota1']}")
    print(f"Nota 2: {aluno['nota2']}")
    print()

The exit would be:

Aluno: Matheus
Nota 1: 9.4
Nota 2: 7.2

Aluno: Julia
Nota 1: 4.7
Nota 2: 8.3

Aluno: Eduardo
Nota 1: 3.2
Nota 2: 2.4

List of namedtuple

Gathering

from collections import namedtuple

listaAlunos = []

Aluno = namedtuple("Aluno", "aluno nota1 nota2")

for i in range(0, 3):
   nome = input('Nome do Aluno: ')
   nota1 = float(input('Nota 1: '))
   nota2 = float(input('Nota 2: '))
   listaAlunos.append(Aluno(aluno=nome, nota1=nota1, nota2=nota2))
   print('\n')

Stored data

[Aluno(aluno='Matheus', nota1=9.4, nota2=7.2),
 Aluno(aluno='Julia', nota1=4.7, nota2=8.3), 
 Aluno(aluno='Eduardo', nota1=3.2, nota2=2.4)
]

To print

for aluno in listaAlunos:
    print(f"Aluno : {aluno.aluno}")
    print(f"Nota 1: {aluno.nota1}")
    print(f"Nota 2: {aluno.nota2}")

The way out would be the same as before.

Another possibility would be to store in dictionary, where the key was the name of the student. The structure was like this:

{
 "Matheus": {
             "nota1": 9.4,
             "nota2": 7.2
            },
 "Julia": {
           "nota1": 4.7,
           "nota2": 8.3
          },
 "Eduardo": {
             "nota1": 3.2,
             "nota2": 2.4
            }
}

This is also feasible, but can complicate if you want to list students with a score of 1 less than 5, for example

For this case the list structure containing dictionaries is the most appropriate, as you can use the filter

Simply put, we would have:

listaAlunos = [{'aluno': 'Matheus', 'nota1': 9.4, 'nota2': 7.2}, {'aluno': 'Julia', 'nota1': 4.7, 'nota2': 8.3}, {'aluno': 'Eduardo', 'nota1': 3.2, 'nota2': 2.4}]

for aluno in filter(lambda aluno: aluno["nota1"] > 5, listaAlunos):
    print(aluno)

Being the result:

{'aluno': 'Matheus', 'nota1': 9.4, 'nota2': 7.2}

In the above case, lambda may be replaced by a function

def nota1_maior_que_cinco(aluno):
    return aluno["nota1"] > 5

for aluno in filter(nota1_maior_que_cinco, listaAlunos):
    print(aluno)
{'aluno': 'Matheus', 'nota1': 9.4, 'nota2': 7.2}

I hope I’ve helped

  • Thank you very much for the help, I’m still on the list about lists and this exercise could only be done using this knowledge. But I’m already analyzing this part of dictionaries and namedtuple that you sent to better understand.

Browser other questions tagged

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