List Comprehensions & Reading Data From a Text File:

  • List comprehension combines the for loop and creation of new elements into one line, and automatically appends each new element.
    • For example, imagine we want to assign 92 numbers to a list of students.

students.txt

1Harpua
2Suzy
3Wilson
4Hoshi
5Jackie
6Jennifer
7Dimitri
  • To use the list comprehension syntax, begin with a descriptive name for the list, such as, studentID. Next open a set of square brackets and define the expression of the values you want to store in the new list. Then, write a for loop to generate 92 numbers to feed into the expression and close the square brackets.

Python list comprehension code reading student names from a file and assigning each a random 9-digit ID number

  • Output:

[‘Harpua - 922645998’, ‘Suzy - 923305795’, ‘Wilson - 920108469’, ‘Hoshi - 927307107’, ‘Jackie - 926171619’, ‘Jennifer - 925673401’, ‘Dimitri - 927690276’]