Natalie
Natalie

Reputation: 51

How do i print the first index of every list except for the header row?

grades = [
    ['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
    ['Thorny', '100', '90', '80'],
    ['Mac', '88', '99', '111'],
    ['Farva', '45', '56', '67'],
    ['Rabbit', '59', '61', '67'],
    ['Ursula', '73', '79', '83'],
    ['Foster', '89', '97', '101']
]

I want to create a new list named Students which has all the student names except for the header.

I tried:

students = [item[0] for item in grades]

but this gives me the header "students" as well.

Upvotes: 2

Views: 175

Answers (4)

NoorJafri
NoorJafri

Reputation: 1827

Although it has been answered but if headers are not sorted and occurs at some other position:

# Look for header containing certain string
header = lambda s: "Student" not in s

# Get everything from the list except containing header
students = [i for i in grades if header(i)]

Upvotes: 0

e.doroskevic
e.doroskevic

Reputation: 2167

The above solution uses list comprehansion. This solution utilizes a more comon way you'd see it being writen in other programming languages.

  students = []
  for data in grades[1:]:
      students.append(data[0])

Upvotes: 0

blue note
blue note

Reputation: 29099

Just throw away the first line.

 students = students[1:]

Upvotes: 0

Matt S
Matt S

Reputation: 15374

You're close. You simply need to limit the grades in your statement:

students = [item[0] for item in grades[1:]]

This will iterate over grades starting with the second item (index of 1) to the end (nothing after the :).

Upvotes: 7

Related Questions