210201 Python TIL - List/Dictionary Comprehension

Python

  • List / Dictionary Comprehension**

    Python을 더 Python스럽게 작성하기위해서 이 Comprehension을 이해하고 적절히 잘 사용해야한다.

    • List Comprehension

      • 리스트의 각 요소에 2를 곱해서 새로운 리스트 생성하기 (for-loop + list comprehension)
      1
      2
      3
      4
      5
      6
      7
      numbers = [1, 2, 3, 4, 5]
      new_numbers = []
      for i in numbers:
      new_numbers.append(i*2)
      print(new_numbers)
      # list comprehension을 사용해서 아래와 같이 간단하게 작성을 해줄 수 있다.
      new_numbers = [i*2 for i in numbers]
Read more