Reading-Notes


Project maintained by eslamakram Hosted on GitHub Pages — Theme by mattgraham

List Comprehensions in Python

List comprehension is a powerful and concise method for creating lists in Python that becomes essential the more you work with lists, and lists of lists

Notes about Lists Comprehensions

List comprehension methods are an elegant way to create and manage lists. In Python, list comprehensions are a more compact way of creating lists. More flexible than for loops, list comprehension is usually faster than other methods.

syntax: my_new_list = [ expression for item in list ]

  1. Python’s range() method as a way to create a list of digits.
  2. Identify numbers in a string using the isdigit() method
  3. Separating the characters in a string using letter for letter in string statement
  4. Reading file with list comprehensions using line for line in file reading

examples:

# open the file in read-only mode
file = open("dreams.txt", 'r')
poem = [ line for line in file ]

for line in poem:
    print(line)