Guest User

List Comprehension r/learnpython

a guest
Sep 6th, 2024
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | Source Code | 0 0
  1.  
  2. # < ==========================================
  3. # < Functions and Methods
  4. # < ==========================================
  5.  
  6. def append(_list, item) -> None:
  7.     """Method to add an item to a list"""
  8.     # Built-in code goes here
  9.     return None
  10.  
  11. def double(number) -> int:
  12.     """Function to double a number"""
  13.     return number * 2
  14.  
  15. # < ==========================================
  16. # < Test One
  17. # < ==========================================
  18.  
  19. output = [double(i) for i in range(1, 11)]
  20. print(output)
  21. # output = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
  22. # The left side of double(i) for i in range(1, 11) is evaluated each time
  23. # Each item in the output list is evaluated to be the return of double(i), which returns an integer
  24.  
  25. # < ==========================================
  26. # < Test Two
  27. # < ==========================================
  28.  
  29. squares = []
  30. print(f"Squares list before running [squares.append(i * i) for i in range(1, 11)]: {squares}")
  31. # Squares list before running [squares.append(i * i) for i in range(1, 11)]: []
  32.  
  33. output = [squares.append(i * i) for i in range(1, 11)]
  34. print(output)
  35. # output = [None, None, None, None, None, None, None, None, None, None]
  36. # The left side of squares.append(i * i) for i in range(1, 11) is evaluated each time
  37. # Each item in the output list is evaluated to be the return of squares.append(i * i), which returns None
  38.  
  39. print(f"Squares list after running [squares.append(i * i) for i in range(1, 11)]: {squares}")
  40. # Squares list after running [squares.append(i * i) for i in range(1, 11)]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Advertisement
Add Comment
Please, Sign In to add comment