'Python grok learning lists

Hi I am working on a module for Grok learning and it gave me a problem to create a program that takes a list of students names and prints each name out individually and alphabetically as a class roll (each name capitalized).

#pseudo
# ask for students and store in 'students'
# split 'students', which is now a list
# sorts the list alphabetically
# print('Class roll')
# for i in students
# print i . capitalize

data = input('Students: ')
students = data.split()
students = students.sort()
print('Class Roll')
for i in students:
  print(i.capitalize())

and essentially it gives me this error message that I don't understand:

Students: a c b d
Class Roll
Traceback (most recent call last):
  File "program.py", line 13, in <module>
    for i in students:
TypeError: 'NoneType' object is not iterable

Comments are fine.



Solution 1:[1]

When you call sort on a list it sorts in place, rather than returning a sorted list. Try it without assignment, i.e.:

data = input('Students: ')
students = data.split()
students.sort() # this line is changed
print('Class Roll')
for i in students:
  print(i.capitalize())

Solution 2:[2]

This should fix your problem. Simply remove the equal sign since .sort() transforms the list itself.

data = input('Students: ')
students = data.split()
students.sort()
print('Class Roll')
for i in students:
  print(i.capitalize())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SamR
Solution 2 March_G