{"id":13821106,"url":"https://github.com/buttercrab/wtfpython-ko","last_synced_at":"2025-04-15T20:44:01.190Z","repository":{"id":44942325,"uuid":"231020447","full_name":"buttercrab/wtfpython-ko","owner":"buttercrab","description":"놀라운 예제들을 통해서 파이썬을 탐험하고 이해해보세요!","archived":false,"fork":false,"pushed_at":"2022-01-17T10:04:29.000Z","size":1391,"stargazers_count":132,"open_issues_count":0,"forks_count":13,"subscribers_count":4,"default_branch":"3.0","last_synced_at":"2025-03-29T01:12:03.620Z","etag":null,"topics":["documentation","gotchas","python","snippets","wats","wtf"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"wtfpl","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/buttercrab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"code-of-conduct.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-12-31T03:39:37.000Z","updated_at":"2025-03-24T11:21:10.000Z","dependencies_parsed_at":"2022-08-30T14:50:46.202Z","dependency_job_id":null,"html_url":"https://github.com/buttercrab/wtfpython-ko","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/buttercrab%2Fwtfpython-ko","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/buttercrab%2Fwtfpython-ko/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/buttercrab%2Fwtfpython-ko/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/buttercrab%2Fwtfpython-ko/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/buttercrab","download_url":"https://codeload.github.com/buttercrab/wtfpython-ko/tar.gz/refs/heads/3.0","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249151949,"owners_count":21221155,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["documentation","gotchas","python","snippets","wats","wtf"],"created_at":"2024-08-04T08:01:15.298Z","updated_at":"2025-04-15T20:44:01.160Z","avatar_url":"https://github.com/buttercrab.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"\u003e ## 번역\n\u003e\n\u003e 번역에 참여하고 싶으시면 [Github Discussion](https://github.com/buttercrab/wtfpython-ko/discussions)을 방문하세요!\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"/images/logo.png\" alt=\"\"\u003e\u003c/p\u003e\n\u003ch1 align=\"center\"\u003eWhat the f*ck Python! 😱\u003c/h1\u003e\n\u003cp align=\"center\"\u003e놀라운 예제들을 통해서 파이썬 탐험하고 이해하기\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\u003ca href=\"https://github.com/satwikkansal/wtfpython\"\u003e영어 English(원문)\u003c/a\u003e | \u003ca href=\"https://github.com/leisurelicht/wtfpython-cn\"\u003e중국어 中文\u003c/a\u003e\u003c/p\u003e\n\n다른 읽는 방법: [인터랙티브](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython)\n\n설계가 잘된 고급 인터프리터 언어인 파이썬에는 프로그래머를 위한 편의 기능이 많습니다. 하지만 간혹 어떤 파이썬 코드들은 실행 결과가 이상해보일 때도 있습니다.\n\n이 문서는 직관적이지 않거나 덜 알려진 기능을 사용하는 예제들에 대해 그 이면의 동작을 정확하게 설명합니다.\n\n아래의 예제들이 WTF 까지는 아닐 수도 있지만, 파이썬의 잘 몰랐던 부분을 보여드릴 수는 있을 것입니다. 이런 식으로 공부하는 것이 프로그래밍 언어의 내부를 알게되는데 효과적이라고 생각합니다. 여러분도 동의하게 되실거라 믿습니다!\n\n만약 파이썬의 고인물이라면 첫눈에 예제의 의미를 파악해보세요. 아마 이미 경험한 적이 있는 코드일 수도 있겠습니다. 그렇다면 옛 추억을 떠으로게 해드린 셈이 되겠네요! :sweat_smile:\n\n추신: 예전에 읽었는데 다시 오신 분이라면 [여기서](https://github.com/satwikkansal/wtfpython/releases/) 바뀐 부분을 확인할 수 있습니다.\n\n추신 2: [옮긴이의 말](https://github.com/buttercrab/wtfpython-ko/blob/3.0/translator.md)을 읽는 것을 추천합니다.\n\n그럼, 시작합니다!\n\n# 목차\n\n\u003c!-- Generated using \"markdown-toc -i README.md --maxdepth 3\"--\u003e\n\n\u003c!-- toc --\u003e\n\n- [예제의 구성](#예제의-구성)\n  - [▶ 빛나는 제목](#-빛나는-제목)\n- [사용방법](#사용방법)\n- [👀 예제](#-예제)\n  - [\"머리가 아플수도 있어요!\" 단원](#머리가-아플수도-있어요-단원)\n    - [▶ 먼저 처음 것들부터 \\*](#-먼저-처음-것들부터-)\n    - [▶ 문자열은 가끔 헷갈려요](#-문자열은-가끔-헷갈려요)\n    - [▶ 연결된 연산들을 조심하세요](#-연결된-연산들을-조심하세요)\n    - [▶ `is` 연산자를 안 쓰는 방법](#-is-연산자를-안-쓰는-방법)\n    - [▶ 해시 브라우니](#-해시-브라우니)\n    - [▶ 깊이 들어가면 우리는 다 똑같아.](#-깊이-들어가면-우리는-다-똑같아)\n    - [▶ 질서 속의 무질서 \\*](#-질서-속의-무질서-)\n    - [▶ 계속 시도해 보세요... \\*](#-계속-시도해-보세요-)\n    - [▶ 무엇을 위해서(for)?](#-무엇을-위해서for)\n    - [▶ 실행되는 시간의 차이](#-실행되는-시간의-차이)\n    - [▶ `is not ...` 은 `is (not ...)`이 아니다](#-is-not--은-is-not-이-아니다)\n    - [▶ X가 첫 번째 시도에서 승리하는 틱택토!](#-x가-첫-번째-시도에서-승리하는-틱택토)\n    - [▶ 달라붙는 출력 함수](#-달라붙는-출력-함수)\n    - [▶ 닭이 먼저일까, 달걀이 먼저일까 \\*](#-닭이-먼저일까-달걀이-먼저일까-)\n    - [▶ 서브 클래스의 관계](#-서브-클래스의-관계)\n    - [▶ 메소드의 같음과 동일함](#-메소드의-같음과-동일함)\n    - [▶ 참 거짓의 반복 \\*](#-참-거짓의-반복-)\n    - [▶ 놀라운 콤마](#-놀라운-콤마)\n    - [▶ 문자열과 백슬래시](#-문자열과-백슬래시)\n    - [▶ 매듭이 아니야!](#-매듭이-아니야)\n    - [▶ 반쪽 3중 따옴표 문자열](#-반쪽-3중-따옴표-문자열)\n    - [▶ 불린의 문제점이 뭐야?](#-불린의-문제점이-뭐야-)\n    - [▶ 클래스 속성과 인스턴스 속성](#-클래스-속성과-인스턴스-속성)\n    - [▶ yielding None](#-yielding-none)\n    - [▶ Yielding from... return! \\*](#-yielding-from-return-)\n    - [▶ Nan-재귀성 \\*](#-nan-재귀성-)\n    - [▶ 불변을 변형하기!](#-불변을-변형하기)\n    - [▶ 외부 범위에서 사라지는 변수](#-외부-범위에서-사라지는-변수)\n    - [▶ 미스테리한 키 타입 형 변환](#-미스테리한-키-타입-형-변환)\n    - [▶ 여러분이 맞출 수 있는지 한번 볼까요?](#-여러분이-맞출-수-있는지-한번-볼까요)\n  - [\"미끄러운 비탈길\" 단원](#미끄러운-비탈길-단원)\n    - [▶ 딕셔너리가 반복 중일 때 수정하기](#-딕셔너리가-반복-중일-때-수정하기)\n    - [▶ 완강한 `del` 연산자](#-완강한-del-연산자)\n    - [▶ 범위를 벗어난 변수](#-범위를-벗어난-변수)\n    - [▶ 반복하는 동안 리스트의 아이템을 삭제하기](#-반복하는-동안-리스트의-아이템을-삭제하기)\n    - [▶ 반복자의 손실되는 zip \\*](#-반복자의-손실되는-zip-)\n    - [▶ 루프 변수가 유출되고 있습니다!](#-루프-변수가-유출되고-있습니다)\n    - [▶ 기본 가변인수를 조심하세요!](#-기본-가변인수를-조심하세요)\n    - [▶ 여러 예외들을 잡기](#-여러-예외들을-잡기)\n    - [▶ 같은 피연산자, 다른 이야기!](#-같은-피연산자-다른-이야기)\n    - [▶ 이름 확인은 클래스 범위를 무시합니다](#-이름-확인은-클래스-범위를-무시합니다)\n    - [▶ 모래밭에서 바늘찾기 \\*](#-모래밭에서-바늘찾기-)\n    - [▶ 나눠봅시다 \\*](#-나눠봅시다-)\n    - [▶ 제멋대로 가져오기 \\*](#-제멋대로-가져오기-)\n    - [▶ 다 정렬되었나요? \\*](#-다-정렬되었나요-)\n    - [▶ 자정은 존재하지 않나요?](#-자정은-존재하지-않나요)\n  - [\"숨겨진 보물들!\" 단원](#숨겨진-보물들-단원)\n    - [▶ 파이썬, 날 날게해줄 수 있니?](#-파이썬-날-날게해줄-수-있니)\n    - [▶ `goto`, 하지만 왜?](#-goto-하지만-왜)\n    - [▶ 마음 단단히 먹으세요!](#-마음-단단히-먹으세요)\n    - [▶ 평생 친근한 아저씨 같은 언어를 만나봅시다](#-평생-친근한-아저씨-같은-언어를-만나봅시다)\n    - [▶ 파이썬 조차 사랑이 복잡하다는 것을 이해합니다](#-파이썬-조차-사랑이-복잡하다는-것을-이해합니다)\n    - [▶ 네, 존재합니다!](#-네-존재합니다)\n    - [▶ Ellipsis \\*](#-ellipsis-)\n    - [▶ Inpinity](#-inpinity)\n    - [▶ 망쳐봅시다](#-망쳐봅시다)\n  - [\"겉모습은 기만적입니다!\" 단원](#겉모습은-기만적입니다-단원)\n    - [▶ 줄 건너뛰기?](#-줄-건너뛰기)\n    - [▶ 순간이동](#-순간이동)\n    - [▶ 음, 뭔가 수상한데...](#-음-뭔가-수상한데)\n  - [\"기타 등등\" 단원](#기타-등등-단원)\n    - [▶ `+=` 가 더 빨라요](#--가-더-빨라요)\n    - [▶ 거대한 문자열을 만들어봐요!](#-거대한-문자열을-만들어봐요)\n    - [▶ dict 검색 속도 느려지게 하기 \\*](#-dict-검색-속도-느려지게-하기-)\n    - [▶ `dict` 인스턴스 부풀리기 \\*](#-dict-인스턴스-부풀리기-)\n    - [▶ 사소한 것들 \\*](#-사소한-것들-)\n- [기여하기](#기여하기)\n- [감사의 말](#감사의-말)\n- [🎓 License](#-license)\n  - [친구들을 놀라게 해보세요!](#친구들을-놀라게-해보세요)\n  - [Need a pdf version?](#Need-a-pdf-version-)\n\n\u003c!-- tocstop --\u003e\n\n# 예제의 구성\n\n모든 예제는 아래와 같은 구조로 이루어져 있습니다.\n\n\u003e ### ▶ 빛나는 제목\n\u003e\n\u003e ```py\n\u003e # 예제 세팅\n\u003e # 마법 같은 일을 기대하세요...\n\u003e ```\n\u003e\n\u003e **출력 결과 (유효한 파이썬 버전들):**\n\u003e\n\u003e ```py\n\u003e \u003e\u003e\u003e 입력\n\u003e 놀라운 결과\n\u003e ```\n\u003e\n\u003e 놀라운 결과에 대한 한 줄 설명이 있을 수도 있습니다.\n\u003e\n\u003e #### 💡 설명:\n\u003e\n\u003e - 무엇이 일어나고 있는지와 왜 일어나는지에 대한 간략한 설명\n\u003e\n\u003e ```py\n\u003e # 설명을 도울 예제\n\u003e ```\n\u003e\n\u003e **출력 결과 (유효한 파이썬 버전들):**\n\u003e\n\u003e ```py\n\u003e \u003e\u003e\u003e 입력 # 놀라운 결과의 이해를 돕기 위한 예제\n\u003e # 이해 가능한 결과\n\u003e ```\n\n**참고:** 여기에 있는 모든 예제는 파이썬 3.5.2 인터렉티브 인터프리터에서 테스트 되었고 추가적으로 명시되어 있지 않은 이상 모든 버전에서 작동할 것입니다.\n\n# 사용방법\n\n예제들을 순서대로 읽어내려가는 것을 권장하고 예제마다:\n\n- 예제의 코드를 잘 읽어보세요. 만약 파이썬 고인물이라면 대부분 결과가 어떻게 될지 미리 알고 있을 것입니다.\n- 결과를 읽고,\n  - 예상한 결과와 실제 결과가 맞는지 확인해 보세요.\n  - 결과와 그 작동원리에 대한 정확한 원리를 알고 있나요?\n  * 만약 아니라면 (상관없어요), 큰 숨을 한 번 들이마시고, 설명을 읽어보세요 (그래도 이해하지 못했다면, [여기](https://github.com/satwikkansal/wtfpython/issues/new)에 이슈를 작성해주세요).\n  * 알고 있다면, 자신을 한번 토닥여주고 다음 예제로 넘어가세요.\n\n추신: [pypi 패키지](https://pypi.python.org/pypi/wtfpython)를 사용하면 command line에서도 이 문서를 읽을 수 있습니다.\n\n```sh\n$ pip install wtfpython -U\n$ wtfpython\n```\n\n---\n\n# 👀 예제\n\n## \"머리가 아플수도 있어요!\" 단원\n\n### ▶ 먼저 처음 것들부터 \\*\n\n\u003c!-- Example ID: d3d73936-3cf1-4632-b5ab-817981338863 --\u003e\n\u003c!-- read-only --\u003e\n\n어떤 이유에서인지, 파이썬 3.8의 Walrus 연산자 (`:=`) 가 꽤 알려지게 되었습니다. 확인해봅시다.\n\n1\\.\n\n```py\n# 파이썬 3.8+\n\n\u003e\u003e\u003e a = \"wtf_walrus\"\n'wtf_walrus'\n\u003e\u003e\u003e a\n'wtf_walrus'\n\n\u003e\u003e\u003e a := \"wtf_walrus\"\nFile \"\u003cstdin\u003e\", line 1\n    a := \"wtf_walrus\"\n      ^\nSyntaxError: invalid syntax\n\n\u003e\u003e\u003e (a := \"wtf_walrus\") # 이건 잘 작동하네요\n\u003e\u003e\u003e a\n'wtf_walrus'\n```\n\n2 \\.\n\n```py\n# 파이썬 3.8+\n\n\u003e\u003e\u003e a = 6, 9\n\u003e\u003e\u003e a\n(6, 9)\n\n\u003e\u003e\u003e (a := 6, 9)\n\u003e\u003e\u003e a\n6\n\n\u003e\u003e\u003e a, b = 6, 9 # 전형적인 언패킹\n\u003e\u003e\u003e a, b\n(6, 9)\n\u003e\u003e\u003e (a, b = 16, 19) # 이런\n  File \"\u003cstdin\u003e\", line 1\n    (a, b = 6, 9)\n          ^\nSyntaxError: invalid syntax\n\n\u003e\u003e\u003e (a, b := 16, 19) # 이것은 이상한 3-튜플을 출력합니다.\n(6, 16, 19)\n\n\u003e\u003e\u003e a # a가 아직도 안 바뀌었네요?\n6\n\n\u003e\u003e\u003e b\n16\n```\n\n#### 💡 설명\n\n**간단한 walrus 연산자 설명**\n\nwalrus 연산자 (`:=`) 는 파이썬 3.8에서 소개되었으며, 변수에 할당하면서 연산을 하고 싶을 때 유용하게 쓰일 수 있습니다.\n\n```py\ndef some_func():\n\t\t# 많은 계산을 하는 함수라고 가정합시다.\n        # time.sleep(1000)\n        return 5\n\n# 그래서\nif some_func():\n        print(some_func()) # 같은 계산이 두 번 이루어지므로 안 좋은 방법입니다.\n\n# 또는\na = some_func()\nif a:\n    print(a)\n\n# 대신에 이렇게 간단하게 쓸 수 있습니다.\nif a := some_func():\n        print(a)\n```\n\n**출력 결과 (\u003e 3.8):**\n\n```py\n5\n5\n5\n```\n\n이 연산자는 한 줄의 코드를 아끼고 `some_func`를 두 번 호출하는 것을 방지할 수 있습니다.\n\n- (walrus 연산자를 사용한) 괄호로 묶이지 않은 \"할당문(assignment expression)\"은 컴파일러의 상위 단계에서 제한되므로 첫 번째 줄 `a := \"wtf_walrus\"`에서 `SyntaxError`가 발생합니다. 괄호로 묶게 되면 예상했던 대로 작동하고 `a`에 값을 할당하게 됩니다.\n\n- 정상적으로, `=` 연산자를 포함한 표현식에서는 괄호로 둘러싸는 것이 허용되지 않기 때문에, `(a, b = 6, 9)`에서 syntax error가 발생합니다.\n\n- walrus 연산자는 `Name`이 유효한 식별자(identifier)이고 `expr`이 유효한 표현식 일 때, `Name := expr`로 사용됩니다. 따라서 패킹과 언패킹은 지원되지 않습니다. 그러므로,\n\n  - `(a := 6, 9)`는 `((a := 6), 9)`와 같고 결국 `(a, 9)` (`a`의 값이 6 일때) 와 같게 됩니다.\n\n    ```py\n    \u003e\u003e\u003e (a := 6, 9) == ((a := 6), 9)\n    True\n    \u003e\u003e\u003e x = (a := 696, 9)\n    \u003e\u003e\u003e x\n    (696, 9)\n    \u003e\u003e\u003e x[0] is a # 둘 다 메모리의 같은 위치를 가리키고 있습니다.\n    True\n    ```\n\n  - 비슷하게, `(a, b := 16, 19)`는 `(a, (b := 16), 19)`와 같게 되고 이는 단순한 3-튜플과 같습니다.\n\n---\n\n### ▶ 문자열은 가끔 헷갈려요\n\n\u003c!-- Example ID: 30f1d3fc-e267-4b30-84ef-4d9e7091ac1a ---\u003e\n\n1\\.\n\n```py\n\u003e\u003e\u003e a = \"some_string\"\n\u003e\u003e\u003e id(a)\n140420665652016\n\u003e\u003e\u003e id(\"some\" + \"_\" + \"string\") # 두 id가 같네요\n140420665652016\n```\n\n2\\.\n\n```py\n\u003e\u003e\u003e a = \"wtf\"\n\u003e\u003e\u003e b = \"wtf\"\n\u003e\u003e\u003e a is b\nTrue\n\n\u003e\u003e\u003e a = \"wtf!\"\n\u003e\u003e\u003e b = \"wtf!\"\n\u003e\u003e\u003e a is b\nFalse\n\n```\n\n3\\.\n\n```py\n\u003e\u003e\u003e a, b = \"wtf!\", \"wtf!\"\n\u003e\u003e\u003e a is b # 3.7.x 버전을 제외하고 모든 버전에서 이렇게 작동합니다.\nTrue\n\n\u003e\u003e\u003e a = \"wtf!\"; b = \"wtf!\"\n\u003e\u003e\u003e a is b # 어디서 실행시키는지에 따라 True 혹은 False가 출력될 것입니다. (파이썬 쉘 / ipython / 파이썬 스크립트)\nFalse\n```\n\n```py\n# 이번에는 some_file.py 파일에서 실행시켜봅시다.\na = \"wtf!\"\nb = \"wtf!\"\nprint(a is b)\n\n# 모듈을 실행시키면 True를 출력하네요.\n```\n\n4\\.\n\n**출력 결과 (\u003c 3.7 )**\n\n```py\n\u003e\u003e\u003e 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'\nTrue\n\u003e\u003e\u003e 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'\nFalse\n```\n\n말이 되는 거 같죠?\n\n#### 💡 설명:\n\n- 첫 번째와 두 번째 코드에서의 결과는 새로운 객체를 항상 만드는 것보다 이미 존재하고 바뀌지 않는 객체를 사용하려고 하는 CPython 최적화 때문에 그렇습니다. (문자열 interning이라고 부릅니다)\n- interning이 되고 난 다음, 많은 변수는 같은 메모리에 있는 문자열을 가리키고 있을 겁니다. (메모리를 줄이게 됩니다)\n- 위의 코드들을 보면, 문자열은 알아서 interning이 됩니다. 구현 방식에 따라서 알아서 interning이 될 것인지 결정됩니다. 알아서 interning이 될 것인지 예측해볼 몇 가지 규칙이 있습니다:\n  - 길이가 0과 1인 모든 문자열은 interning이 됩니다.\n  - 문자열은 컴파일 시간에 interning이 됩니다. (`'wtf'`은 interning이 되지만 `''.join(['w', 't', 'f'])`은 interning이 되지 않습니다)\n  - 아스키 문자, 숫자, 언더바 이외의 문자로 이루어져 있으면 interning이 되지 않습니다. 그래서 `'wtf!'`이 `!` 때문에 interning이 되지 않았습니다. CPython에서의 구현은 [여기](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)서 확인할 수 있습니다.\n    ![image](/images/string-intern/string_intern.png)\n- `a`와 `b`가 같은 줄에서 `\"wtf!\"`의 값으로 할당된다면, 파이썬 인터프리터가 새로운 객체를 만들고 두 번째 변수도 가리키게 만듭니다. 그런데 만약 이 작업을 다른 줄에서 한다면, 파이썬 인터프리터는 이미 `\"wtf!\"`가 객체로 존재한다는 사실을 모릅니다 (왜냐하면 `\"wtf!\"`는 interning이 되지 않았기 때문입니다). interning은 컴파일 시간에 작동하는 최적화입니다. 이 최적화는 CPython 3.7.x 버전들에는 적용되지 않았습니다. (더 많은 정보는 이 [이슈](https://github.com/satwikkansal/wtfpython/issues/100)를 확인하세요).\n- IPython과 같은 인터랙티브 환경에서는 하나의 컴파일 유닛(unit)이 하나의 표현식이고 모듈일 때는 모듈 전체일 때도 있습니다. `a, b = \"wtf!\", \"wtf!\"`은 하나의 표현식이지만 `a = \"wtf!\"; b = \"wtf!\"`은 한 줄에 있는 두 개의 표현식입니다. 그러면 위 예제들의 결과를 설명할 수 있습니다.\n- 네 번째 출력 결과의 갑작스러운 변화는 [핍홀 최적화](https://en.wikipedia.org/wiki/Peephole_optimization)에 의한 것입니다. 즉 `'a'*20`은 실행 시간에 클록수를 줄이기 위해 컴파일 시간에 `aaaaaaaaaaaaaaaaaaaa`로바뀝니다. 핍홀 최적화는 문자열의 길이가 20 이하일 때만 일어납니다 (`'a'*10**10`의 결과로 `.pyc`파일의 크기를 생각해보세요). [여기](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288)에 그에 대한 구현이 있습니다.\n- 참고: 파이썬 3.7에서는 새로운 AST 최적화 새로운 로직으로 핍홀 최적화가 빠졌습니다. 그래서 세 번째 코드가 파이썬 3.7에서는 작동하지 않았습니다. [여기](https://bugs.python.org/issue11549)에서 더 자세히 알아보세요.\n\n---\n\n### ▶ 연결된 연산들을 조심하세요\n\n\u003c!-- Example ID: 07974979-9c86-4720-80bd-467aa19470d9 ---\u003e\n\n```py\n\u003e\u003e\u003e (False == False) in [False] # 말이 되네요\nFalse\n\u003e\u003e\u003e False == (False in [False]) # 이것도 말이 됩니다\nFalse\n\u003e\u003e\u003e False == False in [False] # 이건 뭐죠?\nTrue\n\n\u003e\u003e\u003e True is False == False\nFalse\n\u003e\u003e\u003e False is False is False\nTrue\n\n\u003e\u003e\u003e 1 \u003e 0 \u003c 1\nTrue\n\u003e\u003e\u003e (1 \u003e 0) \u003c 1\nFalse\n\u003e\u003e\u003e 1 \u003e (0 \u003c 1)\nFalse\n```\n\n#### 💡 설명:\n\nhttps://docs.python.org/2/reference/expressions.html#not-in 에 따라서\n\n\u003e 형식적으로, a, b, c, ..., y, z가 표현식이고 op1, op2, ..., opN이 비교 연산자라면, 각 식이 한번에 평가된다는 점을 제외하고 a op1 b op2 c ... y opN z는 a op1 b and b op2 c and ... y opN z에 해당합니다.\n\n위의 예시와 같은 결과들은 이상해 보일지도 모르지만, `a == b == c`나 `0 \u003c= x \u003c= 100`와 같은 표현들은 환상적입니다.\n\n- `False is False is False`는 `(False is False) and (False is False)`와 같습니다.\n- `True is False == False`는 `True is False and False == False`와 같으며 구문의 첫 부분 (`True is False`)가 `False`로 평가되기 때문에 전체 표현식의 결과는 `False`가 됩니다.\n- `1 \u003e 0 \u003c 1`은 `1 \u003e 0 and 0 \u003c 1`과 같아 `True`가 계산됩니다.\n- 표현식 `(1 \u003e 0) \u003c 1`은 `True \u003c 1`과 같으며\n  ```py\n  \u003e\u003e\u003e int(True)\n  1\n  \u003e\u003e\u003e True + 1 #예제와는 관련이 없지만, 재미를 위해서입니다.\n  2\n  ```\n  즉, `1 \u003c 1`의 결과는 `False`입니다.\n\n---\n\n### ▶ `is` 연산자를 안 쓰는 방법\n\n\u003c!-- Example ID: 230fa2ac-ab36-4ad1-b675-5f5a1c1a6217 ---\u003e\n\n아래 예제는 인터넷에서 매우 유명한 예제로 퍼져있습니다.\n\n1\\.\n\n```py\n\u003e\u003e\u003e a = 256\n\u003e\u003e\u003e b = 256\n\u003e\u003e\u003e a is b\nTrue\n\n\u003e\u003e\u003e a = 257\n\u003e\u003e\u003e b = 257\n\u003e\u003e\u003e a is b\nFalse\n```\n\n2\\.\n\n```py\n\u003e\u003e\u003e a = []\n\u003e\u003e\u003e b = []\n\u003e\u003e\u003e a is b\nFalse\n\n\u003e\u003e\u003e a = tuple()\n\u003e\u003e\u003e b = tuple()\n\u003e\u003e\u003e a is b\nTrue\n```\n\n3\\.\n**출력 결과**\n\n```py\n\u003e\u003e\u003e a, b = 257, 257\n\u003e\u003e\u003e a is b\nTrue\n```\n\n**출력 결과 (파이썬 3.7.x)**\n\n```py\n\u003e\u003e\u003e a, b = 257, 257\n\u003e\u003e a is b\nFalse\n```\n\n#### 💡 설명:\n\n**`is`와 `==`의 차이점**\n\n- `is` 연산자는 연산자 양쪽이 같은 객체를 참조하고 있는지를 확인합니다. (즉, 둘이 진짜로 같은지를 확인합니다).\n- `==` 연산자는 양쪽의 값을 비교하여 이 둘이 같은지를 확인합니다.\n- 그래서 `is`는 참조의 동등을, `==`는 값의 동등을 확인합니다. 다음 예제로 정리해보면,\n  ```py\n  \u003e\u003e\u003e class A: pass\n  \u003e\u003e\u003e A() is A() # 이 둘은 메모리상에 다른 곳에 있는 두 빈 객체입니다.\n  False\n  ```\n\n**`256`은 존재하는 객체이지만 `257`은 아닙니다**\n\n파이썬을 시작하게 되면, `-5`부터 `256`까지의 수들은 할당됩니다. 이 수들은 많이 사용되기 때문에 미리 준비하는 것입니다.\n\nhttps://docs.python.org/3/c-api/long.html 에서 인용한 글입니다.\n\n\u003e 현 구현은 -5부터 256까지의 정수들을 담는 배열을 만듭니다. 만약 이 범위 안에 있는 정수를 만들게 되면 이미 존재하는 객체의 참조를 반환합니다. 그래서 1의 값을 바꾸는 것이 가능할 것입니다. 아마도 이 경우는 파이썬의 행동은 정의되지 않을 것입니다. :-)\n\n```py\n\u003e\u003e\u003e id(256)\n10922528\n\u003e\u003e\u003e a = 256\n\u003e\u003e\u003e b = 256\n\u003e\u003e\u003e id(a)\n10922528\n\u003e\u003e\u003e id(b)\n10922528\n\u003e\u003e\u003e id(257)\n140084850247312\n\u003e\u003e\u003e x = 257\n\u003e\u003e\u003e y = 257\n\u003e\u003e\u003e id(x)\n140084850247440\n\u003e\u003e\u003e id(y)\n140084850247344\n```\n\n여기서 인터프리터는 `y = 257`을 실행할 때 위에서 벌써 `257`을 가지는 정수를 만들었다는 것을 알 정도로 똑똑하지 않아서 메모리에 새로운 객체를 만들게 됩니다.\n\n빈 튜플과 같이 다른 **변하지 않는** 객체에 대해서도 비슷한 최적화가 적용됩니다. 배열은 변할 수 있어서, `[] is []`는 항상 `False`를 반환하고 `() is ()`는 항상 `True`를 반환합니다. 이는 두 번째 예제를 성명합니다. 이제 세 번쨰로 넘어가볼까요?\n\n**같은 줄에서 같은 값으로 초기화할 때 `a`와 `b` 둘 다 같은 객체를 참조합니다.**\n\n**출력 결과**\n\n```py\n\u003e\u003e\u003e a, b = 257, 257\n\u003e\u003e\u003e id(a)\n140640774013296\n\u003e\u003e\u003e id(b)\n140640774013296\n\u003e\u003e\u003e a = 257\n\u003e\u003e\u003e b = 257\n\u003e\u003e\u003e id(a)\n140640774013392\n\u003e\u003e\u003e id(b)\n140640774013488\n```\n\n- a와 b가 같은 줄에서 `257`로 할당될 때, 파이썬 인터프리터는 새로운 객체를 만듦과 동시에 두 번째 변수가 참조하게 됩니다. 이것을 다른 줄에서 한다면, 인터프리터는 `257`이 이미 있는지 알지 못합니다.\n\n- 이 현상은 컴파일러 최적화이고 특별히 인터랙티브 환경에서만 적용됩니다. 인터프리터에 두 줄을 입력하게 되면, 각각 컴파일되며, 각각 최적화됩니다. 만약 이를 `.py`파일에서 시도한다면, 한 번에 컴파일되기 때문에 이 현상을 보지 못합니다. 이 최적화는 정수에만 국한된 것이 아니라 문자열(\"문자열은 가끔 헷갈려요\"를 확인해보세요.)과 실수와 같이 변하지 않는 자료 구조에도 적용됩니다.\n\n  ```py\n  \u003e\u003e\u003e a, b = 257.0, 257.0\n  \u003e\u003e\u003e a is b\n  True\n  ```\n\n- 왜 파이썬 3.7에서는 작동되지 않나요? 간단히 말하자면 컴파일러 최적화는 구현하기 나름이기 때문입니다. (즉, 버전이나 운영체제 등에 따라 바뀔 수 있어요) 아직 이 문제를 일으킨 정확한 이유를 찾지 못했지만, 이 [이슈](https://github.com/satwikkansal/wtfpython/issues/100)를 확인해보세요.\n\n---\n\n### ▶ 해시 브라우니\n\n\u003c!-- Example ID: eb17db53-49fd-4b61-85d6-345c5ca213ff ---\u003e\n\n1\\.\n\n```py\nsome_dict = {}\nsome_dict[5.5] = \"JavaScript\"\nsome_dict[5.0] = \"Ruby\"\nsome_dict[5] = \"Python\"\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e some_dict[5.5]\n\"JavaScript\"\n\u003e\u003e\u003e some_dict[5.0] # \"Python\"이 \"Ruby\"를 사라지게 했네요.\n\"Python\"\n\u003e\u003e\u003e some_dict[5]\n\"Python\"\n\n\u003e\u003e\u003e complex_five = 5 + 0j\n\u003e\u003e\u003e type(complex_five)\ncomplex\n\u003e\u003e\u003e some_dict[complex_five]\n\"Python\"\n```\n\n그래서, 왜 파이썬이 여기저기서 발견되나요?\n\n#### 💡 설명\n\n- 파이썬 딕셔너리 키의 유일성은 키가 서로 동일한지가 아니라, 동등한 값으로 결정됩니다. 그래서 `5`, `5.0`, 그리고 `5 + 0j`가 서로 다른 타입이더라도 같은 값을 가지기 때문에 같은 딕셔너리나 집합안에 있을 수 없습니다. 그 중 하나를 삽입하게 되면 (`KeyError`을 발생시키는 것이 아닌) 동등한 원소를 발견하는 것을 성공하게 됩니다.\n  ```py\n  \u003e\u003e\u003e 5 == 5.0 == 5 + 0j\n  True\n  \u003e\u003e\u003e 5 is not 5.0 is not 5 + 0j\n  True\n  \u003e\u003e\u003e some_dict = {}\n  \u003e\u003e\u003e some_dict[5.0] = \"Ruby\"\n  \u003e\u003e\u003e 5.0 in some_dict\n  True\n  \u003e\u003e\u003e (5 in some_dict) and (5 + 0j in some_dict)\n  True\n  ```\n- 이는 한 원소의 값을 지정할 때도 적용됩니다. 그래서 `some_dict[5] = \"Python\"`을 하게 되면, 파이썬은 동등한 키인 `5.0 -\u003e \"Ruby\"`를 찾게 되고, 그 값을 덮어쓰게 됩니다. \n  ```py\n  \u003e\u003e\u003e some_dict\n  {5.0: 'Ruby'}\n  \u003e\u003e\u003e some_dict[5] = \"Python\"\n  \u003e\u003e\u003e some_dict\n  {5.0: 'Python'}\n  ```\n- 그러면 우리는 어떻게 (`5.0` 대신) `5`인 키를 업데이트 할 수 있을까요? 이는 값을 업데이트 하는 것으로는 할 수 없지만, 먼저 키를 지우고 (`del some_dict[5.0]`), 다시 실수 `5.0` 대신 정수 `5`설정하는 (`some_dict[5]`) 것을 통해 할 수 있습니다. 이런 경우는 드물긴 하겠네요.\n\n- 파이썬은 `5.0`을 포함하고 있는 딕셔너리에서 어떻게 `5`를 찾았을까요? 파이썬은 모든 원소를 보지 않고 해시 함수를 이용해 상수 시간에 해결합니다. 파이썬이 `foo`라는 키를 딕셔너리에서 찾을 때, 먼저 `hash(foo)`를 계산합니다. (이는 상수시간에 계산됩니다). 파이썬에서는 동등한 값은 같은 해시값을 가지므로 ([관련 문서](https://docs.python.org/ko/3/reference/datamodel.html#object.__hash__)), `5`, `5.0`, 그리고 `5 + 0j`는 같은 해시 값을 가지게 됩니다. \n  ```py\n  \u003e\u003e\u003e 5 == 5.0 == 5 + 0j\n  True\n  \u003e\u003e\u003e hash(5) == hash(5.0) == hash(5 + 0j)\n  True\n  ```\n  **관련 정보:** 반대는 참이 아닐 수가 있습니다: 해시 값이 같은 두 객체는 동등하지 않을 수 있습니다. (이는 [해시 충돌](https://ko.wikipedia.org/wiki/%ED%95%B4%EC%8B%9C_%EC%B6%A9%EB%8F%8C)이라고 알려져 있고 해싱의 상수 시간의 성능을 저하시킬 수 있습니다. )\n\n---\n\n### ▶ 깊이 들어가면 우리는 다 똑같아.\n\n\u003c!-- Example ID: 8f99a35f-1736-43e2-920d-3b78ec35da9b ---\u003e\n\n```py\nclass WTF:\n  pass\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e WTF() == WTF() # 두 인스턴스는 같을 수 없습니다\nFalse\n\u003e\u003e\u003e WTF() is WTF() # 메모리 위에서도 다르네요\nFalse\n\u003e\u003e\u003e hash(WTF()) == hash(WTF()) # 해시는 _당연히_ 같아야 합니다\nTrue\n\u003e\u003e\u003e id(WTF()) == id(WTF())\nTrue\n```\n\n#### 💡 설명:\n\n- `id`가 호출되었을 때, 파이썬에서 `WTF` 객체를 만들고 `id` 함수로 넘겨줍니다. `id` 함수는 그 객체의 아이디(`id`, 메모리상의 위치)를 가져오고 객체를 버립니다. 객체는 파괴됩니다.\n- 만약 이것을 두 번 한다면, 파이썬은 두 번째 객체도 같은 메모리에 할당하게 됩니다. (CPython에서는) `id`가 메모리의 위치를 객체의 아이디로 쓰기 때문에 두 아이디는 같게 됩니다.\n- 그래서 객체의 아이디는 객체가 파괴되지 않는 한 고유합니다. 객체가 파괴된 후 또는 생성되기 이전에는 다른 것이 같은 아이디를 가질 수도 있습니다.\n- 그러면 왜 `is` 연산자는 `False`라고 출력했을까요? 이 코드를 보세요.\n\n  ```py\n  class WTF(object):\n    def __init__(self): print(\"I\")\n    def __del__(self): print(\"D\")\n  ```\n\n  **출력 결과:**\n\n  ```py\n  \u003e\u003e\u003e WTF() is WTF()\n  I\n  I\n  D\n  D\n  False\n  \u003e\u003e\u003e id(WTF()) == id(WTF())\n  I\n  D\n  I\n  D\n  True\n  ```\n\n  여러분도 보셨다시피 객체들이 만들어지고 파괴되는 순서가 다르게 됩니다.\n\n---\n\n### ▶ 질서 속의 무질서 \\*\n\n\u003c!-- Example ID: 91bff1f8-541d-455a-9de4-6cd8ff00ea66 ---\u003e\n\n```py\nfrom collections import OrderedDict\n\ndictionary = dict()\ndictionary[1] = 'a'; dictionary[2] = 'b';\n\nordered_dict = OrderedDict()\nordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n\nanother_ordered_dict = OrderedDict()\nanother_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n\nclass DictWithHash(dict):\n    \"\"\"\n\t__hash__ 마법을 구현하는 dict\n    \"\"\"\n    __hash__ = lambda self: 0\n\nclass OrderedDictWithHash(OrderedDict):\n    \"\"\"\n\t__hash__ 마법을 구현하는 OrderedDict\n    \"\"\"\n    __hash__ = lambda self: 0\n```\n\n**출력 결과**\n\n```py\n\u003e\u003e\u003e dictionary == ordered_dict # 만약 a == b 이고,\nTrue\n\u003e\u003e\u003e dictionary == another_ordered_dict # b == c 이면\nTrue\n\u003e\u003e\u003e ordered_dict == another_ordered_dict # 왜 c == a 가 아닐까요?\nFalse\n\n# 집합(set)은 유일한 원소들만 가지고 있으므로,\n# 위의 딕셔너리로 집합을 만들고 어떤 일이 일어나는지 알아봅시다.\n\n\u003e\u003e\u003e len({dictionary, ordered_dict, another_ordered_dict})\nTraceback (most recent call last):\n  File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\nTypeError: unhashable type: 'dict'\n\n# 딕셔너리는 __hash__가 구현되어있지 않으므로 그런것 같네요.\n# 그러면 위에서 만든 래퍼(wrapper) 클래스를 써봅시다.\n\u003e\u003e\u003e dictionary = DictWithHash()\n\u003e\u003e\u003e dictionary[1] = 'a'; dictionary[2] = 'b';\n\u003e\u003e\u003e ordered_dict = OrderedDictWithHash()\n\u003e\u003e\u003e ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n\u003e\u003e\u003e another_ordered_dict = OrderedDictWithHash()\n\u003e\u003e\u003e another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n\u003e\u003e\u003e len({dictionary, ordered_dict, another_ordered_dict})\n1\n\u003e\u003e\u003e len({ordered_dict, another_ordered_dict, dictionary}) # 순서를 바꿔봅시다.\n2\n```\n\n무슨 일이 벌어지고 있는거죠?\n\n#### 💡 설명:\n\n- `dictionary` 그리고 `ordered_dict`, `another_ordered_dict`가 자동적으로 같지 않은 이유는 `OrderedDict` 클래스에서 `__eq__` 메소드가 구현된 방식 때문입니다. [도큐먼트](https://docs.python.org/3/library/collections.html#ordereddict-objects)에서\n  \u003e OrderedDict 오브젝트이 같음을 확인하는 방법은 순서와 관련이 있고 `list(od1.items())==list(od2.items())`로 구현되어 있습니다. `OrderedDict` 오프젝트와 다른 매핑 오프젝트들의 같음을 확인하는 방법은 순서와 상관있습니다.\n- 위와 같이 동작하는 이유는 `OrderedDict` 오브젝트가 바로 보통의 딕셔너리가 사용되는 곳에 사용될 수 있게 하기 위해서 입니다.\n- 그러면 왜 `set` 오브젝트에서 순서를 바꾼것이 왜 길이에 영향을 미친 것일까요? 같음을 확인하는 함수가 잘 구현되어 있지 않기 때문입니다. 집합(set)은 유일한 원소들의 순서를 고려하지 않은 자료구조이므로, 각 원소를 삽입하는 순서는 상관이 없어야 합니다. 하지만 이 경우에는 상관이 있네요. 한번 깊이 들어가 봅시다.\n\n  ```py\n  \u003e\u003e\u003e some_set = set()\n  \u003e\u003e\u003e some_set.add(dictionary) # 이것들은 위의 코드에서의 매핑 오브젝트들입니다\n  \u003e\u003e\u003e ordered_dict in some_set\n  True\n  \u003e\u003e\u003e some_set.add(ordered_dict)\n  \u003e\u003e\u003e len(some_set)\n  1\n  \u003e\u003e\u003e another_ordered_dict in some_set\n  True\n  \u003e\u003e\u003e some_set.add(another_ordered_dict)\n  \u003e\u003e\u003e len(some_set)\n  1\n\n  \u003e\u003e\u003e another_set = set()\n  \u003e\u003e\u003e another_set.add(ordered_dict)\n  \u003e\u003e\u003e another_ordered_dict in another_set\n  False\n  \u003e\u003e\u003e another_set.add(another_ordered_dict)\n  \u003e\u003e\u003e len(another_set)\n  2\n  \u003e\u003e\u003e dictionary in another_set\n  True\n  \u003e\u003e\u003e another_set.add(another_ordered_dict)\n  \u003e\u003e\u003e len(another_set)\n  2\n  ```\n\n  그래서 `ordered_dict == another_ordered_dict`이 `False`이고 `ordered_dict`이 `another_set`안에 들어있었으므로 `another_ordered_dict in another_set`이 `False`인 모순으로 인해서 생긴일 입니다.\n\n---\n\n### ▶ 계속 시도해 보세요... \\*\n\n\u003c!-- Example ID: b4349443-e89f-4d25-a109-82616be9d41a ---\u003e\n\n```py\ndef some_func():\n    try:\n        return 'from_try'\n    finally:\n        return 'from_finally'\n\ndef another_func():\n    for _ in range(3):\n        try:\n            continue\n        finally:\n            print(\"Finally!\")\n\ndef one_more_func(): # 알았다!\n    try:\n        for i in range(3):\n            try:\n                1 / i\n            except ZeroDivisionError:\n\t\t\t\t# 여기서 에러를 발생시키고 반복문 밖에서 다뤄보도록 하죠\n                raise ZeroDivisionError(\"A trivial divide by zero error\")\n            finally:\n                print(\"Iteration\", i)\n                break\n    except ZeroDivisionError as e:\n        print(\"Zero division error ocurred\", e)\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e some_func()\n'from_finally'\n\n\u003e\u003e\u003e another_func()\nFinally!\nFinally!\nFinally!\n\n\u003e\u003e\u003e 1 / 0\nTraceback (most recent call last):\n  File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\nZeroDivisionError: division by zero\n\n\u003e\u003e\u003e one_more_func()\nIteration 0\n\n```\n\n#### 💡 설명:\n\n- `return` 또는 `break`, `continue`가 \"try-finally\" 에서의 `try`문 안에서 실행된다면, `finally` 구문도 끝나기 전에 실행됩니다.\n- 함수의 리턴값은 마지막 리턴문에 의해 결정됩니다. `finally` 구문이 항상 마지막에 실행되므로, `finally` 안에 있는 리턴문이 실행됩니다.\n- 여기서 주의할 점은 만약 `finally` 구문 안에서 `return`이나 `break`이 있을 때 임시로 저장된 예외가 없어집니다.\n\n---\n\n### ▶ 무엇을 위해서(for)?\n\n\u003c!-- Example ID: 64a9dccf-5083-4bc9-98aa-8aeecde4f210 ---\u003e\n\n```py\nsome_string = \"wtf\"\nsome_dict = {}\nfor i, some_dict[i] in enumerate(some_string):\n    i = 10\n```\n\n**출력결과:**\n\n```py\n\u003e\u003e\u003e some_dict # 딕셔너리가 나타나네요\n{0: 'w', 1: 't', 2: 'f'}\n```\n\n#### 💡 설명:\n\n- `for` 문은 [파이썬 문법](https://docs.python.org/3/reference/grammar.html)에서 정의되어 있습니다:\n\n  ```\n  for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\n  ```\n\n  `exprlist`는 할당되는 부분입니다. 이는 `{exprlist} = {next_value}`와 같다는 말이고 **각각의 원소에 대해 실행됩니다.**\n  아래에 재미있는 예제가 있습니다.\n\n  ```py\n  for i in range(4):\n      print(i)\n      i = 10\n  ```\n\n  **출력 결과:**\n\n  ```\n  0\n  1\n  2\n  3\n  ```\n\n  반복문이 한 번만 돌기를 기대했나요?\n\n  **💡 설명:**\n\n  - 반복문이 파이썬에서 특별하게 작동하기 때문에 할당문 `i = 10`은 절대로 반복문에 영향을 끼치지 않습니다. 매번 반복하기 전에 반복자(iterator)에 의해 제공된 값(위 경우는 `range(4)`)들이 변수(위 경우는 `i`)에 할당됩니다.\n\n- `enumerate(some_string)` 함수는 반복마다 새로운 값 `i` (하나씩 올라가는 카운터)와 `some_string`에 있는 문자 하나씩을 yield 합니다. 그리고 딕셔너리 `some_dict`에 키가 `i`인 값을 그 문자로 지정합니다. 반복문을 풀어보면 아래처럼 나올 수 있습니다:\n  ```py\n  \u003e\u003e\u003e i, some_dict[i] = (0, 'w')\n  \u003e\u003e\u003e i, some_dict[i] = (1, 't')\n  \u003e\u003e\u003e i, some_dict[i] = (2, 'f')\n  \u003e\u003e\u003e some_dict\n  ```\n\n---\n\n### ▶ 실행되는 시간의 차이\n\n\u003c!-- Example ID: 6aa11a4b-4cf1-467a-b43a-810731517e98 ---\u003e\n\n1\\.\n\n```py\narray = [1, 8, 15]\n# 전형적인 제너레이터(generator) 예제입니다\ngen = (x for x in array if array.count(x) \u003e 0)\narray = [2, 8, 22]\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e print(list(gen)) # 다른 값들은 어디 갔나요?\n[8]\n```\n\n2\\.\n\n```py\narray_1 = [1,2,3,4]\ngen_1 = (x for x in array_1)\narray_1 = [1,2,3,4,5]\n\narray_2 = [1,2,3,4]\ngen_2 = (x for x in array_2)\narray_2[:] = [1,2,3,4,5]\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e print(list(gen_1))\n[1, 2, 3, 4]\n\n\u003e\u003e\u003e print(list(gen_2))\n[1, 2, 3, 4, 5]\n```\n\n3\\.\n\n```py\narray_3 = [1, 2, 3]\narray_4 = [10, 20, 30]\ngen = (i + j for i in array_3 for j in array_4)\n\narray_3 = [4, 5, 6]\narray_4 = [400, 500, 600]\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e print(list(gen))\n[401, 501, 601, 402, 502, 602, 403, 503, 603]\n```\n\n#### 💡 설명\n\n- [제너레이터](https://wiki.python.org/moin/Generators)에서는 `in` 부분은 선언할 때 실행되지만 조건문은 런타임에 실행됩니다.\n- 그래서 런타임 이전에, `array`가 `[2, 8, 22]`로 재할당 되고 `1`, `8`, `15`중에 `8`이 개수가 `0`보다 크므로 제너레이터는 오직 `8`만 yield 합니다.\n- 두 번쨰 예제의 `gen_1`과 `gen_2`의 출력 결과가 다른 이유는 `array_1`과 `array_2`가 재할당되는 방법이 다르기 때문입니다.\n- 첫 번째 경우에는, `array_1`이 새로운 객체인 `[1, 2, 3, 4, 5]`가 할당되고 `in` 부분은 선언할 때 계산되기 때문에 계속 이전 객체인 `[1, 2, 3, 4]`를 가지고 있습니다.\n- 두 번째 경우에는, `array_2`에 슬라이스 객체가 할당될 때 이전의 객체인 `[1, 2, 3, 4]`를 `[1, 2, 3, 4, 5]`로 변화시킵니다. 따라서 `g2`와 `array_2` 모두 같은 (새롭게 `[1, 2, 3, 4, 5]`로 업데이트된) 객체를 가리키고 있습니다.\n- 좋아요, 그런데 지금까지의 로직을 살펴보면, 세 번째 예제의 `list(g)`의 값이 `[11, 21, 31, 12, 22, 32, 13, 23, 33]` 가 되어야 하는 것이 아닌가요? (왜냐하면 `array_3`과 `array_4`가 `array_1`처럼 행동할 테니까요). (오직) `array_4`의 값만이 업데이트되는 이유는 [PEP-289](https://www.python.org/dev/peps/pep-0289/#the-details)에서 설명되어 있습니다\n\n  \u003e for 구문의 가장 바깥쪽 부분만 바로 계산되고, 다른 구문들은 제너레이터가 실행될때까지 참조되는 것이 없습니다.\n\n---\n\n### ▶ `is not ...` 은 `is (not ...)`이 아니다\n\n\u003c!-- Example ID: b26fb1ed-0c7d-4b9c-8c6d-94a58a055c0d ---\u003e\n\n```py\n\u003e\u003e\u003e 'something' is not None\nTrue\n\u003e\u003e\u003e 'something' is (not None)\nFalse\n```\n\n#### 💡 설명\n\n- `is not` 은 단일 이진 연산자이며, 이는 `is`와 `not`을 따로 사용하는 것과는 다른 기능을 합니다.\n- `is not` 연산자는 양쪽의 변수가 동일한 객체를 가리키면 `False`를, 아니면 `True`로 나타납니다.\n- In the example, `(not None)` evaluates to `True` since the value `None` is `False` in a boolean context, so the expression becomes `'something' is True`.\n\n---\n\n### ▶ X가 첫 번째 시도에서 승리하는 틱택토!\n\n\u003c!-- Example ID: 69329249-bdcb-424f-bd09-cca2e6705a7a ---\u003e\n\n```py\n# row를 초기화합니다\nrow = [\"\"] * 3 #row i['', '', '']\n# board를 만듭니다\nboard = [row] * 3\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e board\n[['', '', ''], ['', '', ''], ['', '', '']]\n\u003e\u003e\u003e board[0]\n['', '', '']\n\u003e\u003e\u003e board[0][0]\n''\n\u003e\u003e\u003e board[0][0] = \"X\"\n\u003e\u003e\u003e board\n[['X', '', ''], ['X', '', ''], ['X', '', '']]\n```\n\n우리는 세 개의 `\"X\"`를 할당하지 않았습니다. 그랬나요?\n\n#### 💡 설명:\n\n다음 시각화 자료는 `row` 변수를 초기화할 때 메모리에서 어떠한 일이 일어나는지 보여줍니다.\n\n![image](/images/tic-tac-toe/after_row_initialized.png)\n\n그리고 다음은 `row`를 곱하여 `board`를 초기화할 때, 메모리에서 일어나는 일입니다. (각각의 원소 `board[0]`, `board[1]` 그리고 `board[2]`는 `row`가 참조한 동일한 리스트의 참조자입니다.)\n\n![image](/images/tic-tac-toe/after_board_initialized.png)\n\n위와 같은 현상은 `row`를 사용하지 않고 `board`를 생성하여 해결할 수 있습니다. (이 [이슈](https://github.com/satwikkansal/wtfpython/issues/68)에서 질문되었습니다).\n\n```py\n\u003e\u003e\u003e board = [['']*3 for _ in range(3)]\n\u003e\u003e\u003e board[0][0] = \"X\"\n\u003e\u003e\u003e board\n[['X', '', ''], ['', '', ''], ['', '', '']]\n```\n\n---\n\n### ▶ 달라붙는 출력 함수\n\n\u003c!-- Example ID: 4dc42f77-94cb-4eb5-a120-8203d3ed7604 ---\u003e\n\n1\\.\n\n```py\nfuncs = []\nresults = []\nfor x in range(7):\n    def some_func():\n        return x\n    funcs.append(some_func)\n    results.append(some_func())  # 함수를 호출하고 있다는 것을 놓치지 마세요.\n\nfuncs_results = [func() for func in funcs]\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e results\n[0, 1, 2, 3, 4, 5, 6]\n\u003e\u003e\u003e funcs_results\n[6, 6, 6, 6, 6, 6, 6]\n```\n\n`funcs`에 `some_func`를 추가하기 전의 `x`값은 항상 달랐는데도, 모든 함수가 6을 리턴합니다.\n\n2\\.\n\n```py\n\u003e\u003e\u003e powers_of_x = [lambda x: x**i for i in range(10)]\n\u003e\u003e\u003e [f(2) for f in powers_of_x]\n[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n```\n\n#### 💡 설명\n\n- 반복문 내에서 반복문의 변수를 사용하는 함수를 정의하면, 함수의 클로저는 변수의 값이 아니라 변수 자체에 바인딩됩니다. 따라서 모든 함수가 그 변수에 마지막으로 할당된 값을 사용하게 되죠.\n\n- 원하는 결과를 얻고 싶다면, 반복문의 변수를 함수의 인자로서 넘겨주면 됩니다. **이게 왜 되는 걸까요?** 이렇게 하면 변수가 함수의 스코프 내에서 다시 정의되기 때문입니다.\n\n  ```py\n  funcs = []\n  for x in range(7):\n      def some_func(x=x):\n          return x\n      funcs.append(some_func)\n  ```\n\n  **출력 결과:**\n\n  ```py\n  \u003e\u003e\u003e funcs_results = [func() for func in funcs]\n  \u003e\u003e\u003e funcs_results\n  [0, 1, 2, 3, 4, 5, 6]\n  ```\n\n---\n\n### ▶ 닭이 먼저일까, 달걀이 먼저일까 \\*\n\n\u003c!-- Example ID: 60730dc2-0d79-4416-8568-2a63323b3ce8 ---\u003e\n\n1\\.\n\n```py\n\u003e\u003e\u003e isinstance(3, int)\nTrue\n\u003e\u003e\u003e isinstance(type, object)\nTrue\n\u003e\u003e\u003e isinstance(object, type)\nTrue\n```\n\n그래서, \"궁극적인\" 기본 클래스는 뭘까요? 혼란스러운 점은 이게 끝이 아닙니다.\n\n2\\.\n\n```py\n\u003e\u003e\u003e class A: pass\n\u003e\u003e\u003e isinstance(A, A)\nFalse\n\u003e\u003e\u003e isinstance(type, type)\nTrue\n\u003e\u003e\u003e isinstance(object, object)\nTrue\n```\n\n3\\.\n\n```py\n\u003e\u003e\u003e issubclass(int, object)\nTrue\n\u003e\u003e\u003e issubclass(type, object)\nTrue\n\u003e\u003e\u003e issubclass(object, type)\nFalse\n```\n\n#### 💡 설명\n\n- `type`은 파이썬의 [메타클래스](https://realpython.com/python-metaclasses/)입니다.\n- 파이썬에서 **모든 것은** `object`입니다. 이는 클래스와 인스턴스 모두에게 해당됩니다.\n- `type` 클래스는 `object` 클래스의 메타클래스이고, (`type`을 포함하는) 모든 클래스는 직접적으로든 간접적으로든 `object`를 상속합니다.\n- `object`와 `type` 중에서 진짜 기본 클래스는 존재하지 않습니다. 위의 코드들이 야기하는 혼란은 우리가 이런 관계들(`issubclass`와 `isinstance`)을 파이썬 클래스의 관점에서 생각하고 있기 때문에 발생합니다. `object`와 `type`의 관계는 순수 파이썬만으로는 재현할 수 없습니다. 정확히 말하자면, 아래의 관계는 순수 파이썬만으로 재현하는 것이 불가능합니다.\n  - 클래스 A는 클래스 B의 인스턴스이고, 클래스 B는 클래스 A의 인스턴스입니다.\n  - 클래스 A는 자기 자신의 인스턴스입니다.\n- `object`와 `type`의 이러한 관계(서로가 서로와 자기 스스로의 인스턴스인 것)를 가질 수 있는 건 구현 수준에서의 \"편법\"이 사용되었기 때문입니다.\n\n---\n\n### ▶ 서브 클래스의 관계\n\n\u003c!-- Example ID: 9f6d8cf0-e1b5-42d0-84a0-4cfab25a0bc0 ---\u003e\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e from collections import Hashable\n\u003e\u003e\u003e issubclass(list, object)\nTrue\n\u003e\u003e\u003e issubclass(object, Hashable)\nTrue\n\u003e\u003e\u003e issubclass(list, Hashable)\nFalse\n```\n\n서브 클래스의 관계는 삼단논법을 따라야 하지 않나요? (즉 `A`가 `B`의 서브 클래스이고 `B`가 `C`의 서브 클래스이면 `A`는 `C`의 서브 클래스 _이여야만_ 합니다)\n\n#### 💡 설명:\n\n- 파이썬에서는 서브 클래스의 관계가 삼단논법을 따를 필요가 없습니다. 아무나 자유롭게 메타클래스에 자신만의 `__subclasscheck__`를 만들 수 있습니다.\n- `issubclass(cls, Hashable)`이 호출되면, `cls`나 이의 조상 클래스에서 거짓이 아닌 \"`__hash__`\" 메소드를 찾습니다.\n- `object`가 해싱할 수 있고 `list`는 해싱할 수 없기 때문에, 상속되었다고 보기 힘듭니다.\n- 더 자세한 정보는 [여기](https://www.naftaliharris.com/blog/python-subclass-intransitivity/)에서 찾아볼 수 있습니다.\n\n---\n\n### ▶ 메소드의 같음과 동일함\n\n\u003c!-- Example ID: 94802911-48fe-4242-defa-728ae893fa32 ---\u003e\n\n1.\n\n```py\nclass SomeClass:\n    def method(self):\n        pass\n\n    @classmethod\n    def classm(cls):\n        pass\n\n    @staticmethod\n    def staticm():\n        pass\n```\n\n**출력 결과:*\n\n```py\n\u003e\u003e\u003e print(SomeClass.method is SomeClass.method)\nTrue\n\u003e\u003e\u003e print(SomeClass.classm is SomeClass.classm)\nFalse\n\u003e\u003e\u003e print(SomeClass.classm == SomeClass.classm)\nTrue\n\u003e\u003e\u003e print(SomeClass.staticm is SomeClass.staticm)\nTrue\n```\n\n`classm`을 두 번 접근했을 때, 동등한 객체이지만 _같지는_ 않은 객체가 되네요?\n`SomeClass`의 인스턴스는 어떻게 되는지 한 번 볼까요?:\n\n\u003e 여기서 동등하다는 것은 메모리 상 같은 위치에 있다는 것이고, 같다는 것은 단순하게 값이 같다는 의미입니다. \n\n2.\n\n```py\no1 = SomeClass()\no2 = SomeClass()\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e print(o1.method == o2.method)\nFalse\n\u003e\u003e\u003e print(o1.method == o1.method)\nTrue\n\u003e\u003e\u003e print(o1.method is o1.method)\nFalse\n\u003e\u003e\u003e print(o1.classm is o1.classm)\nFalse\n\u003e\u003e\u003e print(o1.classm == o1.classm == o2.classm == SomeClass.classm)\nTrue\n\u003e\u003e\u003e print(o1.staticm is o1.staticm is o2.staticm is SomeClass.staticm)\nTrue\n```\n\n`SomeClass`의 같은 인스턴스는 `classm`와 `method`를 두 번 접근했을 때, 동등하지만 _같지는_ 않은 객체를 생성합니다.\n\n#### 💡 설명\n\n- 함수는 [디스크립터](https://docs.python.org/ko/3/howto/descriptor.html) 입니다. \n함수가 속성으로 접근되었을 때, 디스크립터가 호출되고, 객체를 가지고 속성으로 가지고 있는 함수를 \"바인딩\" 하는 메소드 객체를 생성합니다. \n만약 호출되면 메소드는 그 함수를 호출하고, 내부적으로 바인드된 객체를 첫 번째 인자로 넘겨줍니다. \n(이 원리로 인해 직접적으로 넘기지 않고 `self`를 첫 번째 인자로 받을 수 있는 것입니다.)\n\n```py\n\u003e\u003e\u003e o1.method\n\u003cbound method SomeClass.method of \u003c__main__.SomeClass object at ...\u003e\u003e\n```\n\n- 속성에 여러번 접근할 때마다 매번 메소드 객체를 만들게 됩니다! \n그래서 `o1.method is o2.method`는 참일 수가 없는 것이죠. \n(인스턴스와 반대되게) 함수를 클래스 속성으로 접근하게 되면 메소드를 생성하지 않게 됩니다. \n그래서 `SomeClass.method is SomeClass.method`는 항상 참입니다. \n\n```py\n\u003e\u003e\u003e SomeClass.method\n\u003cfunction SomeClass.method at ...\u003e\n```\n\n- `classmethod`는 함수를 클래스 메소드로 변환시킵니다. 클래스 메소드는 접근할때 객체 대신에 객체의 _class_ (타입)을 바인드한 메소드 객체를 생성하는 디스크럽터 입니다.\n\n```py\n\u003e\u003e\u003e o1.classm\n\u003cbound method SomeClass.classm of \u003cclass '__main__.SomeClass'\u003e\u003e\n```\n\n- 함수와는 달리, `classmethods`는 클래스 속성으로 접근할 때 (타입이 아닌 클래스를 바인드 합니다) 새로운 메소드를 생성합니다. \n그래서 `SomeClass.classm is SomeClass.classm`는 거짓입니다.\n\n```py\n\u003e\u003e\u003e SomeClass.classm\n\u003cbound method SomeClass.classm of \u003cclass '__main__.SomeClass'\u003e\u003e\n```\n\n- 메소드 객체가 같다는 것은 두 함수가 같고 바인드 되어 있는 객체가 같음을 의미합니다.\n그래서 메모리상 같은 객체가 아님에도 `o1.method == o1.method`는 같습니다.\n- `staticmethod`는 함수를 그대로 리턴하는 \"no-op\" (아무 일도 하지 않는) 디스크립터를 통해 함수를 변형시킵니다.\n어떠한 객체도 생성되지 않으며, `is`로 비교하는 것은 참이 됩니다.\n\n```py\n\u003e\u003e\u003e o1.staticm\n\u003cfunction SomeClass.staticm at ...\u003e\n\u003e\u003e\u003e SomeClass.staticm\n\u003cfunction SomeClass.staticm at ...\u003e\n```\n\n- 파이썬에서 인스턴스 메소드를 호출할 때마다 인자들을 매번 변경하고 맨 앞에 `self`를 넣어주면서 새로운 \"메소드\" 객체를 만드는 것은 속도에 나쁘게 영향을 끼치게 됩니다.\nCPython 3.7은 임시 메소드 객체를 만들지 않고 해결하는 새로운 명령코드를 만들어서 이 문제를 [해결했습니다.](https://bugs.python.org/issue26110).\n이 방법은 함수가 실제로 호출 될 때 사용되므로, 여기 있는 코드들에 영향을 끼치지 않고 여전히 메소드를 생성합니다 :)\n\n---\n\n### ▶ 참 거짓의 반복 \\*\n\n\u003c!-- Example ID: dfe6d845-e452-48fe-a2da-0ed3869a8042 --\u003e\n\n```py\n\u003e\u003e\u003e all([True, True, True])\nTrue\n\u003e\u003e\u003e all([True, True, False])\nFalse\n\n\u003e\u003e\u003e all([])\nTrue\n\u003e\u003e\u003e all([[]])\nFalse\n\u003e\u003e\u003e all([[[]]])\nTrue\n```\n\n왜 이런 참 거짓의 반복이 일어날까요?\n\n#### 💡 설명:\n\n- `all`함수의 구현은 다음과 같습니다\n\n- ```py\n  def all(iterable):\n      for element in iterable:\n          if not element:\n              return False\n      return True\n  ```\n\n- `all([])`은 비어있으므로 `True`를 반환합니다.\n- `all([[]])`은 `not[]`는 True이며 이는 `not False`와 같고, `iterable` 안에 있는 리스트가 비어 있기 때문에 `False`를 반환합니다.\n- `all([[[]]])`와 더 많이 겹친 경우는 `not [[]]`, `not [[[]]]`... 이 `not True`와 동일 하므로 모두 `True`를 반환합니다.\n\n---\n\n### ▶ 놀라운 콤마\n\n\u003c!-- Example ID: 31a819c8-ed73-4dcc-84eb-91bedbb51e58 ---\u003e\n\n**출력 결과 (\u003c 3.6):**\n\n```py\n\u003e\u003e\u003e def f(x, y,):\n...     print(x, y)\n...\n\u003e\u003e\u003e def g(x=4, y=5,):\n...     print(x, y)\n...\n\u003e\u003e\u003e def h(x, **kwargs,):\n  File \"\u003cstdin\u003e\", line 1\n    def h(x, **kwargs,):\n                     ^\nSyntaxError: invalid syntax\n\n\u003e\u003e\u003e def h(*args,):\n  File \"\u003cstdin\u003e\", line 1\n    def h(*args,):\n                ^\nSyntaxError: invalid syntax\n```\n\n#### 💡 설명:\n\n- 파이썬 함수의 정규 파라미터 리스트에 콤마를 남기는 것이 항상 허용되는 것은 아닙니다.\n- 파이썬에서 전달인자 리스트는 선행 콤마(leading commas)들과 후행 콤마(trailing commas)들로 부분적으로 정의되어 있습니다. 이러한 충돌이 콤마가 가운데에 끼게되는 현상을 만들게 되고 결국 아무 규칙에도 맞지 않게 됩니다.\n- **참고:** 후행 콤마 문제는 [파이썬 3.6에서 고쳐졌습니다](https://bugs.python.org/issue9232). 이 [포스트](https://bugs.python.org/issue9232#msg248399)에서는 파이썬에서의 후행 콤마들의 다양한 사용법들이 간결하게 논의하고 있습니다.\n\n---\n\n### ▶ 문자열과 백슬래시\n\n\u003c!-- Example ID: 6ae622c3-6d99-4041-9b33-507bd1a4407b ---\u003e\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e print(\"\\\"\")\n\"\n\n\u003e\u003e\u003e print(r\"\\\"\")\n\\\"\n\n\u003e\u003e\u003e print(r\"\\\")\nFile \"\u003cstdin\u003e\", line 1\n    print(r\"\\\")\n              ^\nSyntaxError: EOL while scanning string literal\n\n\u003e\u003e\u003e r'\\'' == \"\\\\'\"\nTrue\n```\n\n#### 💡 설명\n\n- 보통 파이썬 문자열에서 백슬래시는 특별한 의미의 문자(작은 따옴표나 큰 따옴표, 그리고 백슬래시 그 자체)를 이스케이프하는데 사용됩니다.\n  ```py\n  \u003e\u003e\u003e \"wt\\\"f\"\n  'wt\"f'\n  ```\n- 원시 문자열 리터럴(raw string literal, 접두사 `r`로 나타난다)에서는 백슬래시들이 그대로 출력되지만 그 특성도 그대로 적용됩니다.\n\n  ```py\n  \u003e\u003e\u003e r'wt\\\"f' == 'wt\\\\\"f'\n  True\n  \u003e\u003e\u003e print(repr(r'wt\\\"f')\n  'wt\\\\\"f'\n\n  \u003e\u003e\u003e print(\"\\n\")\n\n  \u003e\u003e\u003e print(r\"\\\\n\")\n  '\\\\n'\n  ```\n\n- 즉, 이는 파서가 원시 문자열에서 백슬래시와 만나면 그 뒤에 문자가 나오기를 예상한다는 것입니다. 그리고 이러한 경우(`print(r\"\\\")`)에서는 백슬래시가 뒤의 따옴표에서 이스케이프하여 파서는 끝나는 따옴표를 찾지 못합니다(따라서 `SyntaxError`이 발생합니다). 이 이유로 원시 문자열의 끝에서 백슬래시를 사용할 수 없습니다.\n\n---\n\n### ▶ 매듭이 아니야!\n\n\u003c!-- Example ID: 7034deb1-7443-417d-94ee-29a800524de8 ---\u003e\n\n```py\nx = True\ny = False\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e not x == y\nTrue\n\u003e\u003e\u003e x == not y\n  File \"\u003cinput\u003e\", line 1\n    x == not y\n           ^\nSyntaxError: invalid syntax\n```\n\n#### 💡 설명:\n\n- 연산자 우선순위는 표현식이 실행되는 것에 영향을 주고 파이썬에서는 `==` 연산자는 `not` 연산자보다 우선순위가 높습니다.\n- 그래서 `not x == y`는 `not (x == y)`와 같고 이는 `not (True == False)`와 같게 되므로 최종적으로 `True`가 됩니다.\n- 하지만 `x == not y`는 `SyntaxError`를 발생시키게 됩니다. 왜냐하면 이는 보통 생각하는 `x == (not y)`가 아니라 `(x == not) y`로 해석되기 때문입니다.\n- 파서는 `not` 토큰이 `not in` 연산자의 일부라고 예상하지만 (왜냐하면 `==`와 `not in` 연산자가 같은 연산자 우선순위를 가지고 있기 때문입니다) `not` 뒤에 `in` 토큰을 찾을 수 없기 때문에 `SyntaxError`를 발생시킵니다.\n\n---\n\n### ▶ 반쪽 3중 따옴표 문자열\n\n\u003c!-- Example ID: c55da3e2-1034-43b9-abeb-a7a970a2ad9e ---\u003e\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e print('wtfpython''')\nwtfpython\n\u003e\u003e\u003e print(\"wtfpython\"\"\")\nwtfpython\n\u003e\u003e\u003e # 다음 표현식은 `SyntaxError`를 발생시킵니다.\n\u003e\u003e\u003e # print('''wtfpython')\n\u003e\u003e\u003e # print(\"\"\"wtfpython\")\n  File \"\u003cinput\u003e\", line 3\n    print(\"\"\"wtfpython\")\n                        ^\nSyntaxError: EOF while scanning triple-quoted string literal\n```\n\n#### 💡 설명:\n\n- 파이썬은 암묵적 [문자열 리터럴 병합 연산](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation) 연산을 지원합니다, 예시로,\n  ```\n  \u003e\u003e\u003e print(\"wtf\" \"python\")\n  wtfpython\n  \u003e\u003e\u003e print(\"wtf\" \"\") # 또는 \"wtf\"\"\"\n  wtf\n  ```\n- `'''` 와 `\"\"\"` 는 파이썬에서 문자열 구분 기호로 파이썬은 후에 문자열 끝맺음 3중 따옴표를 찾지만 찾지 못해 SyntaxError를 발생시킵니다.\n\n---\n\n### ▶ 불린의 문제점이 뭐야?\n\n\u003c!-- Example ID: 0bba5fa7-9e6d-4cd2-8b94-952d061af5dd ---\u003e\n\n1\\.\n\n```py\n# 다양한 데이터 타입 속 불린의 개수와 정수의 개수를 세는 간단한 예제입니다.\nmixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\nintegers_found_so_far = 0\nbooleans_found_so_far = 0\n\nfor item in mixed_list:\n    if isinstance(item, int):\n        integers_found_so_far += 1\n    elif isinstance(item, bool):\n        booleans_found_so_far += 1\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e integers_found_so_far\n4\n\u003e\u003e\u003e booleans_found_so_far\n0\n```\n\n2\\.\n\n```py\n\u003e\u003e\u003e some_bool = True\n\u003e\u003e\u003e \"wtf\" * some_bool\n'wtf'\n\u003e\u003e\u003e some_bool = False\n\u003e\u003e\u003e \"wtf\" * some_bool\n''\n```\n\n3\\.\n\n```py\ndef tell_truth():\n    True = False\n    if True == False:\n        print(\"I have lost faith in truth!\")\n```\n\n**출력 (\u003c 3.x):**\n\n```py\n\u003e\u003e\u003e tell_truth()\nI have lost faith in truth!\n```\n\n#### 💡 설명:\n\n- 파이썬에서 `bool`은 `int`의 서브클래스입니다.\n  ```py\n  \u003e\u003e\u003e issubclass(bool, int)\n  True\n  \u003e\u003e\u003e issubclass(int, bool)\n  False\n  ```\n- 추가로, `True`와 `False`는 `int`의 인스턴스입니다.\n\n  ```py\n  \u003e\u003e\u003e isinstance(True, int)\n  True\n  \u003e\u003e\u003e isinstance(False, int)\n  True\n  ```\n\n- `True`의 정수 값은 `1`이고 `False`의 정수 값은 `0`입니다.\n\n  ```py\n  \u003e\u003e\u003e int(True)\n  1\n  \u003e\u003e\u003e int(False)\n  0\n  ```\n\n- StackOverflow [답변](https://stackoverflow.com/a/8169049/4354153)을 통해 이러한 현상이 발생하는 이유에 대해서 알아보세요.\n\n- 초기에, 파이썬은 `bool` 타입이 없었습니다. (사람들은 0을 거짓으로 쓰고 1과 같은 0이 아닌 수를 참으로 사용했습니다) `True` 그리고 `False`, `bool` 타입은 2.x 버전에서 추가되었지만 호환성을 위해 `True`와 `False`는 상수로 만들어질 수 없었습니다. 이들은 내장 변수이고 다시 할당하는 것이 가능했습니다.\n\n- 파이썬 3은 호환이 안되기 때문에, 문제가 해결되었고 마지막 코드는 파이썬 3.x 에서는 작동하지 않습니다!\n\n---\n\n### ▶ 클래스 속성과 인스턴스 속성\n\n\u003c!-- Example ID: 6f332208-33bd-482d-8106-42863b739ed9 ---\u003e\n\n1\\.\n\n```py\nclass A:\n    x = 1\n\nclass B(A):\n    pass\n\nclass C(A):\n    pass\n```\n\n**Output:**\n\n```py\n\u003e\u003e\u003e A.x, B.x, C.x\n(1, 1, 1)\n\u003e\u003e\u003e B.x = 2\n\u003e\u003e\u003e A.x, B.x, C.x\n(1, 2, 1)\n\u003e\u003e\u003e A.x = 3\n\u003e\u003e\u003e A.x, B.x, C.x # C.x 는 바뀌었지만, B.x 는 바뀌지 않았습니다.\n(3, 2, 3)\n\u003e\u003e\u003e a = A()\n\u003e\u003e\u003e a.x, A.x\n(3, 3)\n\u003e\u003e\u003e a.x += 1\n\u003e\u003e\u003e a.x, A.x\n(4, 3)\n```\n\n2\\.\n\n```py\nclass SomeClass:\n    some_var = 15\n    some_list = [5]\n    another_list = [5]\n    def __init__(self, x):\n        self.some_var = x + 1\n        self.some_list = self.some_list + [x]\n        self.another_list += [x]\n```\n\n**Output:**\n\n```py\n\u003e\u003e\u003e some_obj = SomeClass(420)\n\u003e\u003e\u003e some_obj.some_list\n[5, 420]\n\u003e\u003e\u003e some_obj.another_list\n[5, 420]\n\u003e\u003e\u003e another_obj = SomeClass(111)\n\u003e\u003e\u003e another_obj.some_list\n[5, 111]\n\u003e\u003e\u003e another_obj.another_list\n[5, 420, 111]\n\u003e\u003e\u003e another_obj.another_list is SomeClass.another_list\nTrue\n\u003e\u003e\u003e another_obj.another_list is some_obj.another_list\nTrue\n```\n\n#### 💡 설명:\n\n- 클래스 변수들과 클래스 인스턴스 안에 있는 변수들은 내부에서 클래스 객체의 딕셔너리들로 처리됩니다. 현재 클래스의 딕셔너리에 변수 이름이 없는 경우, 부모 클래스에서 해당 이름을 검색합니다.\n- '+=' 연산자는 새로운 객체를 생성하지 않고 그 자리에서 가변 객체를 수정합니다. 따라서, 한 인스턴스의 속성을 바꾸는 것은 다른 인스턴스들과 클래스 속성에도 영향을 미칩니다.\n\n---\n\n### ▶ yielding None\n\n\u003c!-- Example ID: 5a40c241-2c30-40d0-8ba9-cf7e097b3b53 ---\u003e\n\n```py\nsome_iterable = ('a', 'b')\n\ndef some_func(val):\n    return \"something\"\n```\n\n**출력 결과 (\u003c= 3.7.x):**\n\n```py\n\u003e\u003e\u003e [x for x in some_iterable]\n['a', 'b']\n\u003e\u003e\u003e [(yield x) for x in some_iterable]\n\u003cgenerator object \u003clistcomp\u003e at 0x7f70b0a4ad58\u003e\n\u003e\u003e\u003e list([(yield x) for x in some_iterable])\n['a', 'b']\n\u003e\u003e\u003e list((yield x) for x in some_iterable)\n['a', None, 'b', None]\n\u003e\u003e\u003e list(some_func((yield x)) for x in some_iterable)\n['a', 'something', 'b', 'something']\n```\n\n#### 💡 설명:\n\n- 이것은 CPython에서 제너레이터와 컴프리헨션에서 `yield`를 처리할 때 생기는 버그입니다.\n- 소스와 설명은 여기서 찾아볼 수 있습니다: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n- 관련된 버그 리포트: https://bugs.python.org/issue10544\n- 파이썬 3.8 이상의 버전에서는 리스트 컴프리헨션의 내부에 `yield`를 허용하지 않고 `SyntaxError`를 발생시킵니다.\n\n---\n\n### ▶ Yielding from... return! \\*\n\n\u003c!-- Example ID: 5626d8ef-8802-49c2-adbc-7cda5c550816 ---\u003e\n\n1\\.\n\n```py\ndef some_func(x):\n    if x == 3:\n        return [\"wtf\"]\n    else:\n        yield from range(x)\n```\n\n**출력 결과 (\u003e 3.3):**\n\n```py\n\u003e\u003e\u003e list(some_func(3))\n[]\n```\n\n`\"wtf\"`이 어디로 갓나요? `yield from`의 특수한 효과 때문일까요? 확인해봅시다.\n\n2\\.\n\n```py\ndef some_func(x):\n    if x == 3:\n        return [\"wtf\"]\n    else:\n        for i in range(x):\n          yield i\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e list(some_func(3))\n[]\n```\n\n같은 결과입니다. 이것도 효과가 없습니다.\n\n#### 💡 설명:\n\n- 파이썬 3.3 이후의 버전부터, 내부의 제너레이터와 함께 `return`문을 사용할 수 있게 되었습니다 (이것을 참고하세요 [PEP380](https://www.python.org/dev/peps/pep-0380/)). [공식 문서](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration)에서도 말하고 있습니다.\n\n\u003e \"... 제너레이터 내부의 `return expr`는 제너레이터가 종료될 때 `StopIteration(expr)`을 발생시킵니다.\"\n\n- `some_func(3)`의 경우, `return`문으로 인해 처음부터 `StopIteration`이 발생합니다. `StopIteration` 예외는 자동으로 `list(...)` 래퍼와 `for` 루프의 내부에 잡히게 됩니다. 따라서 위의 두 코드의 결과는 빈 리스트가 됩니다.\n\n- 제너레이터의 `some_func`에서 `[\"wtf\"]`을 얻으려면 `StopIteration` 예외를 잡아야 합니다.\n\n  ```py\n  try:\n      next(some_func(3))\n  except StopIteration as e:\n      some_string = e.value\n  ```\n\n  ```py\n  \u003e\u003e\u003e some_string\n  [\"wtf\"]\n  ```\n\n---\n\n### ▶ Nan-재귀성 \\*\n\n\u003c!-- Example ID: 59bee91a-36e0-47a4-8c7d-aa89bf1d3976 ---\u003e\n\n1\\.\n\n```py\na = float('inf')\nb = float('nan')\nc = float('-iNf')  # 이 문자열은 대소문자를 구분하지 않습니다\nd = float('nan')\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e a\ninf\n\u003e\u003e\u003e b\nnan\n\u003e\u003e\u003e c\n-inf\n\u003e\u003e\u003e float('some_other_string')\nValueError: could not convert string to float: some_other_string\n\u003e\u003e\u003e a == -c # inf==inf\nTrue\n\u003e\u003e\u003e None == None # None == None\nTrue\n\u003e\u003e\u003e b == d # 하지만 nan!=nan 입니다\nFalse\n\u003e\u003e\u003e 50 / a\n0.0\n\u003e\u003e\u003e a / a\nnan\n\u003e\u003e\u003e 23 + b\nnan\n```\n\n2\\.\n\n```py\n\u003e\u003e\u003e x = float('nan')\n\u003e\u003e\u003e y = x / x\n\u003e\u003e\u003e y is y # 정체성은 유지됩니다\nTrue\n\u003e\u003e\u003e y == y # y와 같은 값은 아닙니다\nFalse\n\u003e\u003e\u003e [y] == [y] # 하지만 y를 리스트로 감싸면 같은 값이 됩니다\nTrue\n```\n\n#### 💡 설명:\n\n- `'inf'`와 `'nan'`은 대소문자를 구분하지 않는 특수한 문자열로, 명시적으로 `float` 타입으로 형 변환할 때 수학적 \"무한대\"와 \"숫자가 아님\"을 표현할 때 사용합니다.\n\n- IEEE 표준 `NaN != NaN`을 따르면 파이썬에서 컬렉션 요소들의 재귀성 가정이 깨지게 됩니다. 만약 `x`가 `list`와 같은 컬렉션의 일부면 비교와 같은 구현들은 `x == x`라는 가정에 기반합니다. 이런 가정 때문에 두 요소를 비교할 때 정체성을 먼저 비교하고 (속도가 더 빠르기 때문입니다) 정체성이 일치하지 않을 때만 값을 비교합니다. 다음의 코드가 이것들을 더 확실하게 만들어 줄 겁니다,\n\n  ```py\n  \u003e\u003e\u003e x = float('nan')\n  \u003e\u003e\u003e x == x, [x] == [x]\n  (False, True)\n  \u003e\u003e\u003e y = float('nan')\n  \u003e\u003e\u003e y == y, [y] == [y]\n  (False, True)\n  \u003e\u003e\u003e x == y, [x] == [y]\n  (False, False)\n  ```\n\n  `x`와 `y`의 정체성이 다르기 때문에 값이 고려되고, 비교 결과 `False`가 반환됩니다.\n\n- 흥미로운 읽을거리: [Reflexivity, and other pillars of civilization](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n\n---\n\n### ▶ 불변을 변형하기!\n\n\u003c!-- Example ID: 15a9e782-1695-43ea-817a-a9208f6bb33d ---\u003e\n\n여러분이 파이썬에서 참조가 어떻게 작동하는지 안다면 이건 당연해 보일 수 있습니다.\n\n```py\nsome_tuple = (\"A\", \"tuple\", \"with\", \"values\")\nanother_tuple = ([1, 2], [3, 4], [5, 6])\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e some_tuple[2] = \"change this\"\nTypeError: 'tuple' object does not support item assignment\n\u003e\u003e\u003e another_tuple[2].append(1000) #이건 에러를 만들지 않습니다\n\u003e\u003e\u003e another_tuple\n([1, 2], [3, 4], [5, 6, 1000])\n\u003e\u003e\u003e another_tuple[2] += [99, 999]\nTypeError: 'tuple' object does not support item assignment\n\u003e\u003e\u003e another_tuple\n([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n```\n\n하지만 저는 튜플이 변경 불가능하다 생각했습니다...\n\n#### 💡 설명:\n\n- https://docs.python.org/ko/3/reference/datamodel.html 을 인용하면\n\n  \u003e 불변 시퀸스\n  \u003e\n  \u003e 불변 시퀀스 형의 객체는 일단 만들어진 후에는 변경될 수 없다. (만약 다른 객체로의 참조를 포함하면, 그 객체는 가변일 수 있고, 변경될 수 있다; 하지만, 불변 객체로부터 참조되는 객체의 집합 자체는 변경될 수 없다.)\n\n- `+=` 연산자는 리스트를 그 자리에서 변경합니다. 그 항목 할당이 동작하지 않지만, 예외 발생 시 그 항목은 이미 그 자리에서 변경되었습니다.\n\n---\n\n### ▶ 외부 범위에서 사라지는 변수\n\n\u003c!-- Example ID: 7f1e71b6-cb3e-44fb-aa47-87ef1b7decc8 ---\u003e\n\n```py\ne = 7\ntry:\n    raise Exception()\nexcept Exception as e:\n    pass\n```\n\n**출력 결과 (Python 2.x):**\n\n```py\n\u003e\u003e\u003e print(e)\n# 아무것도 출력하지 않습니다\n```\n\n**출력 결과 (Python 3.x):**\n\n```py\n\u003e\u003e\u003e print(e)\nNameError: name 'e' is not defined\n```\n\n#### 💡 설명:\n\n- 출처: https://docs.python.org/ko/3/reference/compound_stmts.html#except\n\n  예외가 `as target`을 사용해서 대입될 때, `except`절 끝에서 삭제됩니다. 이것은 마치\n\n  ```py\n  except E as N:\n      foo\n  ```\n\n  가 이렇게 변환되는 것과 같습니다\n\n  ```py\n  except E as N:\n      try:\n          foo\n      finally:\n          del N\n  ```\n\n  이것은 except 절 후에 참조하려면 예외를 다른 이름에 대입해야 한다는 뜻입니다. 예외를 제거하는 이유는, 그것에 첨부된 트레이스백으로 인해, 스택 프레임과 참조 순환을 형성해서 다음 가비지 수거가 일어나기 전까지 그 프레임의 모든 지역 변수들을 잡아두기 때문입니다.\n\n- 해당 절들은 파이썬에서 범위가 정해지지 않았습니다. 예시의 모든 것이 동일한 범위에 존재하며 `except` 절의 실행으로 `e` 변수가 삭제되었습니다. 별도의 내부 범위를 가지고 있는 함수들도 마찬가지\b인 데 다음의 예시가 보여줍니다:\n\n  ```py\n  def f(x):\n      del(x)\n      print(x)\n\n  x = 5\n  y = [5, 4, 3]\n  ```\n\n  **출력 결과:**\n\n  ```py\n  \u003e\u003e\u003ef(x)\n  UnboundLocalError: local variable 'x' referenced before assignment\n  \u003e\u003e\u003ef(y)\n  UnboundLocalError: local variable 'x' referenced before assignment\n  \u003e\u003e\u003e x\n  5\n  \u003e\u003e\u003e y\n  [5, 4, 3]\n  ```\n\n- 파이썬 2.x에서는 `e` 변수가 `Exception()` 인스턴스에 할당되므로 출력하려 할 때 아무것도 출력하지 않습니다.\n\n  **출력 결과 (Python 2.x):**\n\n  ```py\n  \u003e\u003e\u003e e\n  Exception()\n  \u003e\u003e\u003e print e\n  # 아무것도 출력되지 않았습니다!\n  ```\n\n---\n\n### ▶ 미스테리한 키 타입 형 변환\n\n\u003c!-- Example ID: 00f42dd0-b9ef-408d-9e39-1bc209ce3f36 ---\u003e\n\n```py\nclass SomeClass(str):\n    pass\n\nsome_dict = {'s': 42}\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e type(list(some_dict.keys())[0])\nstr\n\u003e\u003e\u003e s = SomeClass('s')\n\u003e\u003e\u003e some_dict[s] = 40\n\u003e\u003e\u003e some_dict # 예상: 두개의 다른 key-value 쌍\n{'s': 40}\n\u003e\u003e\u003e type(list(some_dict.keys())[0])\nstr\n```\n\n#### 💡 설명:\n\n- `SomeClass`는 `str` 클래스의 `__hash__` 메소드를 상속받기 때문에 객체 `s`와 문자열 `\"s\"`는 같은 값을 갖게 됩니다.\n- `SomeClass`은 `str` 클래스의 `__eq__` 메소드도 상속받기 때문에 `SomeClass(\"s\") == \"s\"`의 결과는 `True`가 됩니다.\n- 두 객체는 같은 값으로 해싱되어 동일하기 때문에 딕셔너리에서 같은 키로 표현됩니다.\n- 원하는 동작을 위해 `SomeClass`의 `__eq__` 메소드를 다시 정의할 수 있습니다.\n\n  ```py\n  class SomeClass(str):\n    def __eq__(self, other):\n        return (\n            type(self) is SomeClass\n            and type(other) is SomeClass\n            and super().__eq__(other)\n        )\n\n    # 수정된 __eq__를 정의할 때 파이썬은 자동으로 __hash__ 메소드를\n    # 상속받는 것을 중단합니다. 그래서 정의해줄 필요가 있습니다.\n    __hash__ = str.__hash__\n\n  some_dict = {'s':42}\n  ```\n\n  **출력 결과:**\n\n  ```py\n  \u003e\u003e\u003e s = SomeClass('s')\n  \u003e\u003e\u003e some_dict[s] = 40\n  \u003e\u003e\u003e some_dict\n  {'s': 40, 's': 42}\n  \u003e\u003e\u003e keys = list(some_dict.keys())\n  \u003e\u003e\u003e type(keys[0]), type(keys[1])\n  (__main__.SomeClass, str)\n  ```\n\n---\n\n### ▶ 여러분이 맞출 수 있는지 한번 볼까요?\n\n\u003c!-- Example ID: 81aa9fbe-bd63-4283-b56d-6fdd14c9105e ---\u003e\n\n```py\na, b = a[b] = {}, 5\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e a\n{5: ({...}, 5)}\n```\n\n#### 💡 설명:\n\n- [파이썬 언어 레퍼런스](https://docs.python/org/ko/2/reference/simple_stmts.html#assignment-statements)에 따르면, 대입문의 구조는 다음과 같은 형태를 보입니다.\n  ```\n  (target_list \"=\")+ (expression_list | yield_expression)\n  ```\n  그리고\n\n\u003e 대입문은 표현식 목록 (이것이 하나의 표현식일 수도, 쉼표로 분리된 목록일 수도 있는데, 후자의 경우는 튜플이 만들어진다는 것을 기억하라) 의 값을 구하고, 왼쪽에서 오른쪽으로, 하나의 결과 객체를 타깃 목록의 각각에 대입한다.\n\n- `(target_list \"=\")+`의 `+`는 **하나 이상의** 타깃 목록이 있을 수 있음을 의미합니다. 예제의 경우 타깃 목록은 `a, b`, `a[b]` 입니다. (표현식 목록은 정확하게 하나이며 예제의 경우 `{}, 5` 입니다.)\n\n- 표현식 목록을 평가한 후 해당 값은 **왼쪽에서 오른쪽으로** 타깃 목록에 풀어지게 됩니다. 예제의 경우 먼저 `{}, 5`의 튜플이 `a, b`로 풀리고 `a = {}`, `b = 5`가 됩니다.\n\n- `a`는 이제 변경 가능한 객체인 `{}`에 할당됩니다.\n\n- 두 번째 타깃 목록은 `a[b]`입니다. (여러분은 `a`와 `b`가 구문 이전에 정의되지 않아 에러가 발생할 거라 예상할 수 있습니다. 하지만 우리는 방금 `a`에 `{}`, `b`에 `5`를 대입한 사실을 기억하세요)\n\n- 이제 딕셔너리에 있는 키 `5`를 튜플 `({}, 5)`로 설정하여 순환 참조를 생성합니다. (출력의 `{...}`는 `a`가 이미 참조하고 있는 객체를 가리킵니다.) 순화 참조의 다른 간단한 예는 다음과 같습니다.\n\n  ```py\n  \u003e\u003e\u003e some_list = some_list[0] = [0]\n  \u003e\u003e\u003e some_list\n  [[...]]\n  \u003e\u003e\u003e some_list[0]\n  [[...]]\n  \u003e\u003e\u003e some_list is some_list[0]\n  True\n  \u003e\u003e\u003e some_list[0][0][0][0][0][0] == some_list\n  True\n  ```\n\n  우리의 예제에서도 이것과 비슷합니다. (`a[b][0]`은 `a`와 같은 객체입니다.)\n\n- 요약하자면, 예제를 다음과 같이 나눌 수 있습니다.\n  ```py\n  a, b = {}, 5\n  a[b] = a, b\n  ```\n  그리고 순환 참조는 `a[b][0]`이 `a`와 동일한 객체라는 사실에 의해 정당화 될 수 있습니다.\n  ```py\n  \u003e\u003e\u003e a[b][0] is a\n  True\n  ```\n\n---\n\n---\n\n## \"미끄러운 비탈길\" 단원\n\n### ▶ 딕셔너리가 반복 중일 때 수정하기\n\n\u003c!-- Example ID: b4e5cdfb-c3a8-4112-bd38-e2356d801c41 ---\u003e\n\n```py\nx = {0: None}\n\nfor i in x:\n    del x[i]\n    x[i+1] = None\n    print(i)\n```\n\n**출력 결과 (Python 2.7- Python 3.5):**\n\n```\n0\n1\n2\n3\n4\n5\n6\n7\n```\n\n정확히 **8**번 돌고 멈춥니다.\n\n#### 💡 설명:\n\n- 딕셔너리가 반복될 때 동시에 편집할 수 있는 것은 지원되지 않습니다.\n- 8번 반복되는 이유는 더 많은 키를 소유하기 위해 딕셔너리가 크기를 조정하는 지점이기 때문입니다. (우리는 8개의 삭제 항목들이 있으므로, 크기의 조정이 필요합니다) 이는 실제 구현의\b 세부사항입니다.\n- 삭제된 키를 처리하는 과정과 크기의 조정이 이루어지는 시점은 Python의 구현에 따라 다를 수 있습니다.\n- 따라서, 파이썬 2.7 - 3.5 이외의 버전의 경우, 실행 횟수가 8과 다를 수 있습니다. (하지만 횟수가 어떻던 간에, 실행할 때 마다 동일한 결과입니다) [여기](https://github.com/satwikkansal/wtfpython/issues/53) 또는 StackOverflow의 [이 스레드](https://stackoverflow.com/questions/44763802/bug-in-python-dict)에서 이에 관한 토론을 찾을 수 있습니다.\n- 파이썬 3.7.6 이상에서는 이것을 시도할 경우 `RuntimeError: dictionary keys changed during iteration` 예외를 보여줍니다.\n\n---\n\n### ▶ 완강한 `del` 연산자\n\n\u003c!-- Example ID: 777ed4fd-3a2d-466f-95e7-c4058e61d78e ---\u003e\n\u003c!-- read-only --\u003e\n\n```py\nclass SomeClass:\n    def __del__(self):\n        print(\"Deleted!\")\n```\n\n**출력 결과:**\n1\\.\n\n```py\n\u003e\u003e\u003e x = SomeClass()\n\u003e\u003e\u003e y = x\n\u003e\u003e\u003e del x # \"Deleted!\"를 출력해야 합니다\n\u003e\u003e\u003e del y\nDeleted!\n```\n\n휴, 드디어 삭제되었습니다. 여러분은 처음의 `x` 삭제에서 `__del__`이 호출되지 않은 것을 생각하실 수도 있습니다. 이제 예제를 살짝 비틀어 봅시다.\n\n2\\.\n\n```py\n\u003e\u003e\u003e x = SomeClass()\n\u003e\u003e\u003e y = x\n\u003e\u003e\u003e del x\n\u003e\u003e\u003e y # y가 존재하는지 확인합니다\n\u003c__main__.SomeClass instance at 0x7f98a1a67fc8\u003e\n\u003e\u003e\u003e del y # 이전과 같이, \"Deleted!\"를 출력해야 합니다\n\u003e\u003e\u003e globals() # 오, 그렇지 않네요. 우리의 전역변수를 확인해봅시다\nDeleted!\n{'__builtins__': \u003cmodule '__builtin__' (built-in)\u003e, 'SomeClass': \u003cclass __main__.SomeClass at 0x7f98a1a5f668\u003e, '__package__': None, '__name__': '__main__', '__doc__': None}\n```\n\n좋습니다. 이제 삭제되었습니다 :confused:\n\n#### 💡 설명:\n\n- `del x`는 직접적으로 `x.__del__()`을 부르지 않습니다.\n- `del x`가 호출될 때, 파이썬은 `x`에 대한 참조 카운트를 하나씩 줄입니다. 그리고 `x.__del__()`은 x의 참조 카운트가 0에 도달할 때 실행됩니다.\n- 두번째 코드의 출력에서, `y.__del__()` 는 호출되지 않습니다. 왜냐하면 이전의 구문에 (`\u003e\u003e\u003e y`) 대화형 인터프리터가 같은 객체에 대해 또 다른 참조를 만들고, 따라서 `del y`가 호출될 때 참조 카운트가 0에 도달하지 않습니다.\n- `globals`가 호출되면 존재하는 참조가 파괴돼, 이런 이유로 우리는 \"Deleted!\"가 출력되는 것을 볼 수 있습니다. (마침내!)\n\n---\n\n### ▶ 범위를 벗어난 변수\n\n\u003c!-- Example ID: 75c03015-7be9-4289-9e22-4f5fdda056f7 ---\u003e\n\n1\\.\n\n```py\na = 1\ndef some_func():\n    return a\n\ndef another_func():\n    a += 1\n    return a\n```\n\n2\\.\n\n```py\ndef some_closure_func():\n    a = 1\n    def some_inner_func():\n        return a\n    return some_inner_func()\n\ndef another_closure_func():\n    a = 1\n    def another_inner_func():\n        a += 1\n        return a\n    return another_inner_func()\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e some_func()\n1\n\u003e\u003e\u003e another_func()\nUnboundLocalError: local variable 'a' referenced before assignment\n\n\u003e\u003e\u003e some_closure_func()\n1\n\u003e\u003e\u003e another_closure_func()\nUnboundLocalError: local variable 'a' referenced before assignment\n```\n\n#### 💡 설명:\n\n- 범위 내의 변수에 할당하면, 해당 범위의 로컬 변수가 됩니다. 그래서 `a`는 `another_func`의 범위에 국한되지만 이전과 같은 범위에서 초기화 되지 않아 에러가 발생합니다.\n- `another_func`에서 외부 범위의 `a`를 변경하려면, `global` 키워드를 사용하세요.\n\n  ```py\n  def another_func()\n      global a\n      a += 1\n      return a\n  ```\n\n  **출력 결과:**\n\n  ```py\n  \u003e\u003e\u003e another_func()\n  2\n  ```\n\n- In `another_closure_func`, `a` becomes local to the scope of `another_inner_func`, but it has not been initialized previously in the same scope, which is why it throws an error.\n- To modify the outer scope variable `a` in `another_inner_func`, use the `nonlocal` keyword. The nonlocal statement is used to refer to variables defined in the nearest outer (excluding the global) scope.\n\n  ```py\n  def another_func():\n      a = 1\n      def another_inner_func():\n          nonlocal a\n          a += 1\n          return a\n      return another_inner_func()\n  ```\n\n  **Output:**\n\n  ```py\n  \u003e\u003e\u003e another_func()\n  2\n  ```\n\n- The keywords `global` and `nonlocal` tell the python interpreter to not delcare new variables and look them up in the corresponding outer scopes.\n\n- 짧지만 멋진 [이 가이드](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html)를 읽고 네임스페이스와 범위 결정이 파이썬에서 작동하는 방법에 대해 알아보세요.\n\n---\n\n### ▶ 반복하는 동안 리스트의 아이템을 삭제하기\n\n\u003c!-- Example ID: 4cc52d4e-d42b-4e09-b25f-fbf5699b7d4e ---\u003e\n\n```py\nlist_1 = [1, 2, 3, 4]\nlist_2 = [1, 2, 3, 4]\nlist_3 = [1, 2, 3, 4]\nlist_4 = [1, 2, 3, 4]\n\nfor idx, item in enumerate(list_1):\n    del item\n\nfor idx, item in enumerate(list_2):\n    list_2.remove(item)\n\nfor idx, item in enumerate(list_3[:]):\n    list_3.remove(item)\n\nfor idx, item in enumerate(list_4):\n    list_4.pop(idx)\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e list_1\n[1, 2, 3, 4]\n\u003e\u003e\u003e list_2\n[2, 4]\n\u003e\u003e\u003e list_3\n[]\n\u003e\u003e\u003e list_4\n[2, 4]\n```\n\n왜 출력 결과가 `[2, 4]`가 나오는지 알 수 있나요?\n\n#### 💡 설명:\n\n- 반복하고 있는 객체를 바꾸는 것은 좋은 생각이 아닙니다. 올바른 방법은 `list_3[:]`과 같이 복사본을 반복하는 것입니다.\n\n  ```py\n  \u003e\u003e\u003e some_list = [1, 2, 3, 4]\n  \u003e\u003e\u003e id(some_list)\n  139798789457608\n  \u003e\u003e\u003e id(some_list[:]) # 파이썬은 슬라이스된 리스트를 위해 새로운 객체를 생성하는 것을 알 수 있습니다.\n  139798779601192\n  ```\n\n**`del`, `remove`, `pop`의 차이점**\n\n- `del var_name`은 로컬 또는 전역 네임스페이스에서 `var_name`의 바인딩을 삭제합니다. (그래서 `list_1`은 영향 받지 않습니다)\n- `remove`는 특정 인덱스가 아닌 첫번째 일치하는 값을 삭제하는 경우 값을 찾을 수 없으면 `ValueError`를 일으킵니다.\n- `pop`은 특정 인덱스에서 요소를 제거하고 반환하며, 인덱스가 유효하지 않으면 `IndexError`를 일으킵니다.\n\n**왜 `[2, 4]`가 출력되나요?**\n\n- 리스트의 반복은 인덱스별로 이루어지며, `list_2` 또는 `list_4`에서 `1`을 삭제하면, 리스트는 `[2, 3, 4]`가 됩니다. 나머지 요소들은 인덱스가 낮아지게 되어 `2`는 인덱스 0, `3`은 인덱스 1이 됩니다. 다음번 반복은 인덱스 1 (요소 `3`이 됩니다)을 보게 되고, `2`는 건너뛰게 됩니다. 리스트 순서의 모든 대안 요소들도 비슷한 상황이 일어납니다.\n\n* 예제를 설명하는 StackOverflow [스레드](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) 를 참고하였습니다.\n* 파이썬의 딕셔너리에 관련된 비슷한 예제로 이 StackOverflow [스레드](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) 도 참고하세요.\n\n---\n\n### ▶ 반복자의 손실되는 zip \\*\n\n\u003c!-- Example ID: c28ed154-e59f-4070-8eb6-8967a4acac6d ---\u003e\n\n```py\n\u003e\u003e\u003e numbers = list(range(7))\n\u003e\u003e\u003e numbers\n[0, 1, 2, 3, 4, 5, 6]\n\u003e\u003e\u003e first_three, remaining = numbers[:3], numbers[3:]\n\u003e\u003e\u003e first_three, remaining\n([0, 1, 2], [3, 4, 5, 6])\n\u003e\u003e\u003e numbers_iter = iter(numbers)\n\u003e\u003e\u003e list(zip(numbers_iter, first_three))\n[(0, 0), (1, 1), (2, 2)]\n# 지금까지는 좋은데, 나머지도 압축해봅시다\n\u003e\u003e\u003e list(zip(numbers_iter, remaining))\n[(4, 3), (5, 4), (6, 5)]\n```\n\n`numbers` 리스트에서 요소 `3`이 어디로 갔을까요?\n\n#### 💡 설명:\n\n- 파이썬의 [이 문서](https://docs.python.org/3.3/library/functions.html#zip)에서, zip 함수의 대략적인 구현을 살펴봅시다.\n  ```py\n  def zip(*iterables):\n      sentinel = object()\n      iterators = [iter(it) for it in iterables]\n      while iterators:\n          result = []\n          for it in iterators:\n              elem = next(it, sentinel)\n              if elem is sentinel: return\n              result.append(elem)\n          yield tuple(result)\n  ```\n- 그래서 이 함수는 임의의 수의 반복 가능한 객체를 모아 `next` 함수를 호출하여 각각의 항목을 `result` 리스트에 추가하고, 반복 가능한 객체 중 하나가 고갈될 때에 중지합니다.\n- 여기서 주의해야 할 점은 반복 가능한 객체들이 고갈될 때, `result` 리스트에 들어 있는 기존의 요소들이 폐기되는 것입니다. `numbers_iter` 내부의 `3`에 그러한 일이 일어났습니다.\n- `zip`을 사용하여 위와 같은 일을 처리하는 올바른 방법은 다음과 같습니다,\n  ```py\n  \u003e\u003e\u003e numbers = list(range(7))\n  \u003e\u003e\u003e numbers_iter = iter(numbers)\n  \u003e\u003e\u003e list(zip(first_three, numbers_iter))\n  [(0, 0), (1, 1), (2, 2)]\n  \u003e\u003e\u003e list(zip(remaining, numbers_iter))\n  [(3, 3), (4, 4), (5, 5), (6, 6)]\n  ```\n  zip의 첫번째 인자는 가장 적은 요소를 가지고 있어야 합니다.\n\n---\n\n### ▶ 루프 변수가 유출되고 있습니다!\n\n\u003c!-- Example ID: ccec7bf6-7679-4963-907a-1cd8587be9ea ---\u003e\n\n1\\.\n\n```py\nfor x in range(7):\n    if x == 6:\n        print(x, ': for x inside loop')\nprint(x, ': x in global')\n```\n\n**출력 결과:**\n\n```py\n6 : for x inside loop\n6 : x in global\n```\n\n하지만 `x`는 루프의 밖에서 선언된 적이 없습니다...\n\n2\\.\n\n```py\n# 이번엔 먼저 x를 초기화해봅시다\nx = -1\nfor x in range(7):\n    if x == 6:\n        print(x, ': for x inside loop')\nprint(x, ': x in global')\n```\n\n**출력 결과:**\n\n```py\n6 : for x inside loop\n6 : x in global\n```\n\n3\\.\n\n**출력 결과 (Python 2.x):**\n\n```py\n\u003e\u003e\u003e x = 1\n\u003e\u003e\u003e print([x for x in range(5)])\n[0, 1, 2, 3, 4]\n\u003e\u003e\u003e print(x)\n4\n```\n\n**출력 결과 (Python 3.x):**\n\n```py\n\u003e\u003e\u003e x = 1\n\u003e\u003e\u003e print([x for x in range(5)])\n[0, 1, 2, 3, 4]\n\u003e\u003e\u003e print(x)\n1\n```\n\n#### 💡 설명:\n\n- 파이썬에서, for 루프는 루프의 스코프를 사용하고 정의된 루프 변수는 뒤로 남겨둡니다. 이전에 전역 네임스페이스에서 for 루프 변수를 명시적으로 정의한 경우에도 적용됩니다. 이 경우, 기존에 존재하는 변수를 다시 바인딩합니다.\n\n- 파이썬 2.x와 파이썬 3.x의 인터프리터의 출력 결과의 차이는 다음의 [파이썬 3.0의 새로운 기능들](https://docs.python.org/3/whatsnew/3.0.html) 변경 로그에서 확인할 수 있습니다:\n\n  \u003e \"리스트 컴프리헨션은 이제 `[... for var in item1, item2, ...]` 문법을 지원하지 않습니다. 대신 `[... for var in (item1, item2, ...)]`을 사용하세요. 또한 리스트 컴프리헨션은 다른 의미들을 가지고 있는점에 주목해야합니다: 그들은 `list()` 생성 표현식 생성자의 문법 설탕에 가깝고, 특히 루프 제어 변수들은 더 이상 범위 밖으로 유출되지 않습니다.\n\n---\n\n### ▶ 기본 가변인수를 조심하세요!\n\n\u003c!-- Example ID: 7d42dade-e20d-4a7b-9ed7-16fb58505fe9 ---\u003e\n\n```py\ndef some_func(default_arg=[]):\n    default_arg.append(\"some_string\")\n    return default_arg\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e some_func()\n['some_string']\n\u003e\u003e\u003e some_func()\n['some_string', 'some_string']\n\u003e\u003e\u003e some_func([])\n['some_string']\n\u003e\u003e\u003e some_func()\n['some_string', 'some_string', 'some_string']\n```\n\n#### 💡 설명:\n\n- 파이썬에서 함수의 기본 변경 가능한 인수는 함수가 호출될 때마다 실제로 초기화되지 않습니다. 대신, 최근에 할당된 값이 기본값으로 사용됩니다. `some_func`에 `[]`를 인수로 넘겨줄 때 `default_arg`의 기본값이 사용되지 않아 결과가 예상대로 나오게 됩니다.\n\n  ```py\n  def some_func(default_arg=[]):\n      default_arg.append(\"some_string\")\n      return default_arg\n  ```\n\n  **출력 결과:**\n\n  ```py\n  \u003e\u003e\u003e some_func.__defaults__ #이건 함수에 대한 기본 인수값을 보여줍니다\n  ([],)\n  \u003e\u003e\u003e some_func()\n  \u003e\u003e\u003e some_func.__defaults__\n  (['some_string'],)\n  \u003e\u003e\u003e some_func()\n  \u003e\u003e\u003e some_func.__defaults__\n  (['some_string', 'some_string'],)\n  \u003e\u003e\u003e some_func([])\n  \u003e\u003e\u003e some_func.__defaults__\n  (['some_string', 'some_string'],)\n  ```\n\n- 변경 가능한 인수로 인한 버그를 피하는 일반적인 방법으로는 기본값으로 `None`을 지정한 후에 해당 인수에 어떠한 값이 들어오는지 확인하는 것입니다. 예시:\n\n  ```py\n  def some_func(default_arg=None):\n      if default_arg is None:\n          default_arg = []\n      default_arg.append(\"some_string\")\n      return default_arg\n  ```\n\n---\n\n### ▶ 여러 예외들을 잡기\n\n\u003c!-- Example ID: b5ca5e6a-47b9-4f69-9375-cda0f8c6755d ---\u003e\n\n```py\nsome_list = [1, 2, 3]\ntry:\n    # ``IndexError``를 일으킵니다\n    print(some_list[4])\nexcept IndexError, ValueError:\n    print(\"Caught!\")\n\ntry:\n    # ``ValueError``를 일으킵니다\n    some_list.remove(4)\nexcept IndexError, ValueError:\n    print(\"Caught again!\")\n```\n\n**출력 결과 (Python 2.x):**\n\n```py\nCaught!\n\nValueError: list.remove(x): x not in list\n```\n\n**출력 결과 (Python 3.x):**\n\n```py\n  File \"\u003cinput\u003e\", line 3\n    except IndexError, ValueError:\n                     ^\nSyntaxError: invalid syntax\n```\n\n#### 💡 설명\n\n- 예외처리 구문에 여러 개의 예외를 처리하려면, 해당 예외들을 튜플로 묶어 첫 번째 인수로 넘겨줘야 합니다. 두 번째 인수는 선택적 이름으로, 주어진 경우 일어난 예외 인스턴스가 바인딩 됩니다. 예를 들어,\n\n  ```py\n  some_list = [1, 2, 3]\n  try:\n     # ``ValueError``를 일으킵니다\n     some_list.remove(4)\n  except (IndexError, ValueError), e:\n     print(\"Caught again!\")\n     print(e)\n  ```\n\n  **출력 결과 (Python 2.x):**\n\n  ```\n  Caught again!\n  list.remove(x): x not in list\n  ```\n\n  **출력 결과 (Python 3.x):**\n\n  ```py\n    File \"\u003cinput\u003e\", line 4\n      except (IndexError, ValueError), e:\n                                       ^\n  IndentationError: unindent does not match any outer indentation level\n  ```\n\n- 쉼표로 예외에서 변수를 분리하는 방법은 이제는 사용되지 않으며 파이썬 3에서는 작동하지 않습니다; 이 경우 `as`를 사용해야 합니다. 예를 들어,\n\n  ```py\n  some_list = [1, 2, 3]\n  try:\n      some_list.remove(4)\n\n  except (IndexError, ValueError) as e:\n      print(\"Caught again!\")\n      print(e)\n  ```\n\n  **출력 결과:**\n\n  ```\n  Caught again!\n  list.remove(x): x not in list\n  ```\n\n---\n\n### ▶ 같은 피연산자, 다른 이야기!\n\n\u003c!-- Example ID: ca052cdf-dd2d-4105-b936-65c28adc18a0 ---\u003e\n\n1\\.\n\n```py\na = [1, 2, 3, 4]\nb = a\na = a + [5, 6, 7, 8]\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e a\n[1, 2, 3, 4, 5, 6, 7, 8]\n\u003e\u003e\u003e b\n[1, 2, 3, 4]\n```\n\n2\\.\n\n```py\na = [1, 2, 3, 4]\nb = a\na += [5, 6, 7, 8]\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e a\n[1, 2, 3, 4, 5, 6, 7, 8]\n\u003e\u003e\u003e b\n[1, 2, 3, 4, 5, 6, 7, 8]\n```\n\n#### 💡 설명:\n\n- `a += b` 는 항상 `a = a + b`와 같게 동작하지 않습니다. 클래스는 _`op=`_ 연산자를 _다르게_ 구현할 수 있으며, 리스트는 다음과 같습니다.\n\n- `a = a + [5,6,7,8]` 표현식은 새로운 리스트를 생성하여 새로운 리스트에 대한 `a`의 참조를 설정하므로, `b`는 바뀌지 않습니다.\n\n- `a += [5,6,7,8]` 표현식은 실제로 `a`와 `b`가 여전히 내부에서 수정된 목록을 가리키도록 하는 \"확장\" 함수에 대치됩니다.\n\n---\n\n### ▶ 이름 확인은 클래스 범위를 무시합니다\n\n\u003c!-- Example ID: 03f73d96-151c-4929-b0a8-f74430788324 ---\u003e\n\n1\\.\n\n```py\nx = 5\nclass SomeClass:\n    x = 17\n    y = (x for i in range(10))\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e list(SomeClass.y)[0]\n5\n```\n\n2\\.\n\n```py\nx = 5\nclass SomeClass:\n    x = 17\n    y = [x for i in range(10)]\n```\n\n**출력 결과 (Python 2.x):**\n\n```py\n\u003e\u003e\u003e SomeClass.y[0]\n17\n```\n\n**출력 결과 (Python 3.x):**\n\n```py\n\u003e\u003e\u003e SomeClass.y[0]\n5\n```\n\n#### 💡 설명\n\n- 클래스 정의 내에서 중첩된 범위는 클래스 수준에서 바인딩 된 이름을 무시합니다.\n- 생성 표현식은 자체적인 범위를 갖습니다.\n- 파이썬 3.x부터는 리스트 컴프리헨션 또한 자체적인 범위를 갖습니다.\n\n---\n\n### ▶ 모래밭에서 바늘찾기 \\*\n\n\u003c!-- Example ID: 52a199b1-989a-4b28-8910-dff562cebba9 ---\u003e\n\n다음의 시나리오 중 하나 이상을 접해보지 못한 파이써니스트는 한 번도 만나본 적이 없습니다,\n\n1\\.\n\n```py\nx, y = (0, 1) if True else None, None\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e x, y  # (0, 1)이 예상됩니다\n((0, 1), None)\n```\n\n2\\.\n\n```py\nt = ('one', 'two')\nfor i in t:\n    print(i)\n\nt = ('one')\nfor i in t:\n    print(i)\n\nt = ()\nprint(t)\n```\n\n**출력 결과:**\n\n```py\none\ntwo\no\nn\ne\ntuple()\n```\n\n3\\.\n\n```\nten_words_list = [\n    \"some\",\n    \"very\",\n    \"big\",\n    \"list\",\n    \"that\"\n    \"consists\",\n    \"of\",\n    \"exactly\",\n    \"ten\",\n    \"words\"\n]\n```\n\n**출력 결과**\n\n```py\n\u003e\u003e\u003e len(ten_words_list)\n9\n```\n\n4\\. 충분히 강하게 주장하지 않음\n\n```py\na = \"python\"\nb = \"javascript\"\n```\n\n**출력 결과:**\n\n```py\n# 실패 메세지가 있는 assert 구문.\n\u003e\u003e\u003e assert(a == b, \"Both languages are different\")\n# AssertionError가 일어나지 않습니다\n```\n\n5\\.\n\n```py\nsome_list = [1, 2, 3]\nsome_dict = {\n  \"key_1\": 1,\n  \"key_2\": 2,\n  \"key_3\": 3\n}\n\nsome_list = some_list.append(4)\nsome_dict = some_dict.update({\"key_4\": 4})\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e print(some_list)\nNone\n\u003e\u003e\u003e print(some_dict)\nNone\n```\n\n6\\.\n\n```py\ndef some_recursive_func(a):\n    if a[0] == 0:\n        return\n    a[0] -= 1\n    some_recursive_func(a)\n    return a\n\ndef similar_recursive_func(a):\n    if a == 0:\n        return a\n    a -= 1\n    similar_recursive_func(a)\n    return a\n```\n\n**출력 결과:**\n\n```py\n\u003e\u003e\u003e some_recursive_func([5, 0])\n[0, 0]\n\u003e\u003e\u003e similar_recursive_func(5)\n4\n```\n\n#### 💡 설명:\n\n- 1번에서, 예상되는 동작에 대한 올바른 구문은 `x, y = (0, 1) if True else (None, None)`입니다.\n\n- 2번에서, 예상되는 동작에 대한 올바른 구문은 `t = ('one',)` 또는 `t = 'one',` (콤마가 없음)입니다. 그렇지 않으면 인터프리터는 `t`를 `str`로 생각해 문자 별로 반복합니다.\n\n- `()`은 특별한 토큰이며 빈 `tuple`을 의미합니다.\n\n- 3번에서, 여러분들도 이미 알아 차렷겟지만, 리스트의 5번째 요소 (`\"that\"`)의 뒤에 콤마가 빠져있습니다. 그래서 암묵적인 문자열 리터럴의 연결에 의해,\n\n  ```py\n  \u003e\u003e\u003e ten_words_list\n  ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n  ```\n\n- 4번째 코드에서 `AssertionError`가 일어나지 않은 이유는 `a == b` 표현식이 아닌 전체 튜플을 비교하기 때문입니다. 다음의 코드에서 이를 해결할 수 있습니다.\n\n  ```py\n  \u003e\u003e\u003e a = \"python\"\n  \u003e\u003e\u003e b = \"javascript\"\n  \u003e\u003e\u003e assert a == b\n  Traceback (most recent call last):\n      File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\n  AssertionError\n\n  \u003e\u003e\u003e assert (a == b, \"Values are not equal\")\n  \u003cstdin\u003e:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n\n  \u003e\u003e\u003e assert a == b, \"Values are not equal\"\n  Traceback (most recent call last):\n      File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\n  AssertionError: Values aren not equal\n  ```\n\n- 다섯 번째 코드에서, `list.append`, `dict.update`, `list.sort`또는 다른 것들과 같이 아이템의 순서/매핑 객체의 항목을 수정하는 대부분의 메소드입니다. 그 자리에서 객체를 수정한 후 `None`을 반환합니다. 이를 뒷받침하는 근거는 그 자리에서 연산을 시행할 수 있는 경우 객체의 사본을 만드는 것을 피해 성능을 향상하기 위함입니다. ([이것](http://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)을 참조하였습니다)\n\n- 마지막으로, `list`와 같은 가변 객체를 전달은 참조로 호출되는 반면, `int`와 같은 불변 객체는 값으로 호출됩니다.\n\n- 이런 자잘한 것들까지 알고 있으면 장기적으로 디버깅 시간을 절약할 수 있습니다.\n\n---\n\n### ▶ 나눠봅시다 \\*\n\n\u003c!-- Example ID: ec3168ba-a81a-4482-afb0-691f1cc8d65a ---\u003e\n\n```py\n\u003e\u003e\u003e 'a'.split()\n['a']\n\n# 같은 결과입니다\n\u003e\u003e\u003e 'a'.split(' ')\n['a']\n\n# 하지만\n\u003e\u003e\u003e len(''.split())\n0\n\n# 이건 같지 않네요\n\u003e\u003e\u003e len(''.split(' '))\n1\n```\n\n#### 💡 설명:\n\n- 처음에는 split의 기본 구분자가 공백 한 칸 `' '`인 것처럼 보이지만, [문서](https://docs.python.org/2.7/library/stdtypes.html#str.split)에 따르면\n  \u003e sep 이 지정되지 않거나 None 이면, 다른 분할 알고리즘이 적용됩니다: 연속된 공백 문자는 단일한 구분자로 간주하고, 문자열이 선행이나 후행 공백을 포함해도 결과는 시작과 끝에 빈 문자열을 포함하지 않습니다. 결과적으로, 빈 문자열이나 공백만으로 구성된 문자열을 None 구분자로 나누면 [] 를 돌려줍니다.\n  \u003e sep 이 주어지면, 연속된 구분자는 묶이지 않고 빈 문자열을 구분하는 것으로 간주합니다 (예를 들어, '1,,2'.split(',') 는 ['1', '', '2'] 를 돌려줍니다). sep 인자는 여러 문자로 구성될 수 있습니다 (예를 들어, '1\u003c\u003e2\u003c\u003e3'.split('\u003c\u003e') 는 ['1', '2', '3'] 를 돌려줍니다). 지정된 구분자로 빈 문자열을 나누면 [''] 를 돌려줍니다.\n- 다음 코드에서 앞뒤의 공백이 어떻게 처리되는지 알게 되면 명확해질 겁니다,\n  ```py\n  \u003e\u003e\u003e ' a '.split(' ')\n  ['', 'a', '']\n  \u003e\u003e\u003e ' a '.split()\n  ['a']\n  \u003e\u003e\u003e ''.split(' ')\n  ['']\n  ```\n\n---\n\n### ▶ 제멋대로 가져오기 \\*\n\n\u003c!-- Example ID: 83deb561-bd55-4461-bb5e-77dd7f411e1c ---\u003e\n\u003c!-- read-only --\u003e\n\n```py\n# File: module.py\n\ndef some_weird_name_func_():\n    print(\"works!\")\n\ndef _another_weird_name_func():\n    print(\"works!\")\n\n```\n\n**출력 결과**\n\n```py\n\u003e\u003e\u003e from module import *\n\u003e\u003e\u003e some_weird_name_func_()\n\"works!\"\n\u003e\u003e\u003e _another_weird_name_func()\nTraceback (most recent call last):\n  File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\nNameError: name '_another_weird_name_func' is not defined\n```\n\n#### 💡 설명:\n\n- 와일드카드 import는 자주 사용하지 않는 것이 좋습니다. 와일드카드 import에 대해 명확한 첫 번째 이유는 언더스코어로 시작하는 이름이 import 되기 때문입니다. 이로 인해 런타임 중에 에러가 발생할 수 있습니다.\n- 만약 `from ... import a, b, c` 문법을 사용한다면, `NameError`는 발생하지 않을 것입니다.\n  ```py\n  \u003e\u003e\u003e from module import some_weird_name_func_, _another_weird_name_func\n  \u003e\u003e\u003e _another_weird_name_func()\n  works!\n  ```\n- 만약 정말로 와일드카드 import가 사용하고 싶다면, 와일드카드 import를 할 때 사용할 수 있는 공용 객체가 들어 있는 리스트인 `__all__`을 모듈 내에 정의해야 합니다.\n\n  ```py\n  __all__ = ['_another_weird_name_func']\n\n  def some_weird_name_func_():\n      print(\"works!\")\n\n  def _another_weird_name_func():\n      print(\"works!\")\n  ```\n\n  **출력 결과**\n\n  ```py\n  \u003e\u003e\u003e _another_weird_name_func()\n  \"works!\"\n  \u003e\u003e\u003e some_weird_name_func_()\n  Traceback (most recent call last):\n    File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\n  NameError: name 'some_weird_name_func_' is not defined\n  ```\n\n---\n\n### ▶ 다 정렬되었나요? \\*\n\n\u003c!-- Example ID: e5ff1eaf-8823-4738-b4ce-b73f7c9d5511 --\u003e\n\n```py\n\u003e\u003e\u003e x = 7, 8, 9\n\u003e\u003e\u003e sorted(x) == x\nFalse\n\u003e\u003e\u003e sorted(x) == sorted(x)\nTrue\n\n\u003e\u003e\u003e y = reversed(x)\n\u003e\u003e\u003e sorted(y) == sorted(y)\nFalse\n```\n\n#### 💡 설명:\n\n- 파이썬에서 `sorted` 메소드는 항상 리스트를 반환하고, 리스트와 튜플의 비교는 항상 `False`를 반환합니다.\n\n- ```py\n  \u003e\u003e\u003e [] == tuple()\n  False\n  \u003e\u003e\u003e x = 7, 8, 9\n  \u003e\u003e\u003e type(x), type(sorted(x))\n  (tuple, list)\n  ```\n\n- `sorted`와 달리 `reversed` 메소드는 반복자를 반환합니다. 왜 그럴까요? 왜냐하면 정렬은 반복자가 그 자리에서 변경되거나 추가적인 컨테이너(리스트)를 사용해야 하지만, 뒤집는 것은 단순히 끝 인덱스부터 처음까지 반복하면 되기 때문입니다.\n\n- 따라서 `sorted(y) == sorted(y)`를 비교하는 동안에, 처음의 `sorted()`가 호출되면 `y`의 반복자를 소모하고, 다음의 호출에는 빈 리스트가 반환됩니다.\n\n  ```py\n  \u003e\u003e\u003e x = 7, 8, 9\n  \u003e\u003e\u003e y = reversed(x)\n  \u003e\u003e\u003e sorted(y), sorted(y)\n  ([7, 8, 9], [])\n  ```\n\n---\n\n### ▶ 자정은 존재하지 않나요?\n\n\u003c!-- Example ID: 1bce8294-5619-4d70-8ce3-fe0bade690d1 ---\u003e\n\n```py\nfrom datetime import datetime\n\nmidnight = datetime(2018, 1, 1, 0, 0)\nmidnight_time = midnight.time()\n\nnoon = datetime(2018, 1, 1, 12, 0)\nnoon_time = noon.time()\n\nif midnight_time:\n    print(\"Time at midnight is\", midnight_time)\n\nif noon_time:\n    print(\"Time at noon is\", noon_time)\n```\n\n**출력 결과 (\u003c 3.5):**\n\n```py\n('Time at noon is', datetime.time(12, 0))\n```\n\n자정은 출력되지 않습니다.\n\n#### 💡 설명:\n\n파이썬 3.5 이전에, `datetime.time` 객체의 불리언 값은 UTC 기준으로 자정을 나타내는 경우 `False`로 간주하였습니다. 이는 `if obj:` 구문을 사용하우 `obj`가 null 또는 \"비어있음\"인지 확인하는 경우 오류가 발생하기 쉽습니다.\n\n---\n\n---\n\n## \"숨겨진 보물들!\" 단원\n\n이 단원에는 저 같은 초보자들이 (더 이상은 아니지만) 대부분 모르고 있는 파이썬에 대한 덜 알려지고 흥미로운 것들이 몇 가지 포함되어있습니다.\n\n### ▶ 파이썬, 날 날게해줄 수 있니?\n\n\u003c!-- Example ID: a92f3645-1899-4d50-9721-0031be4aec3f ---\u003e\n\n자, 여기 있습니다\n\n```py\nimport antigravity\n```\n\n**출력 결과:**\n쉿... 이건 일급비밀이야.\n\n#### 💡 설명:\n\n- `antigravity` 모듈은 파이썬 개발자들이 추가한 몇 안 되는 이스터에그입니다.\n- `import antigravity` 는 파이썬에 대한 [고전 XKCD 만화](https://xkcd.com/353)을 웹 브라우저에 띄워줍니다.\n- 더 많은 것이 그 안에 있는데, **또 다른 이스터에그가 이스터에그 안에 있습니다**. [코드](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17)를 보게 된다면, [XKCD의 geohashing 알고리즘](https://xkcd.com/426)을 구현하는 함수가 정의되어 있습니다.\n\n---\n\n### ▶ `goto`, 하지만 왜?\n\n\u003c!-- Example ID: 2aff961e-7fa5-4986-a18a-9e5894bd89fe ---\u003e\n\n```py\nfrom goto import goto, label\nfor i in range(9):\n    for j in range(9):\n        for k in range(9):\n            print(\"I am trapped, please rescue!\")\n            if k == 2:\n                goto .breakout # 깊게 중첩된 루프에서 탈출\nlabel .breakout\nprint(\"Freedom!\")\n```\n\n**출력 결과 (Python 2.3):**\n\n```py\nI am trapped, please rescue!\nI am trapped, please rescue!\nFreedom!\n```\n\n#### 💡 설명:\n\n- 파이썬에 `goto`가 추가된 버전은 2004년 4월 1일에 만우절 장난으로 [발표](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html)되었습니다.\n- 현재 버전의 파이썬은 이 모듈을 가지고 있지 않습니다.\n- 비록 이것이 작동하지만, 사용하지 마십시오. 파이썬에는 `goto`가 존재하지 않는 [이유](https://docs.python.org/3/faq/design.html#why-is-there-no-goto)가 있습니다.\n\n---\n\n### ▶ 마음 단단히 먹으세요!\n\n\u003c!-- Example ID: 5c0c75f2-ddd9-4da3-ba49-c4be7ec39acf ---\u003e\n\n만약 여러분이 파이썬에서 스코프를 나타내기 위해 공백을 사용하는 것을 좋아하지 않는 사람 중 한 명이라면, C-스타일의 {}을 가져와 사용할 수 있습니다.\n\n```py\nfrom __future__ import braces\n```\n\n**출력 결과:**\n\n```py\n  File \"some_file.py\", line 1\n    from __future__ import braces\nSyntaxError: not a chance\n```\n\n중괄호? 절대 안돼! 만약 이게 실망스럽다면 자바를 사용하세요. 또 하나 놀라운 것은 `__future__`모듈에서 발생한 `SyntaxError`가 [코드](https://github.com/python/cpython/blob/master/Lib/__future__.py)의 어디에 있는지 찾을 수 있나요?\n\n#### 💡 설명:\n\n- `__future__` 모듈은 일반적으로 미래의 파이썬 버전에서 추가될 기능을 제공합니다. 하지만 이 특정한 맥락에서 \"미래\"는 아이러니합니다.\n- 이것은 이 문제에 대한 커뮤니티의 감정과 관련된 이스터에그입니다.\n- 그 코드는 실제로 [여기](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) `future.c` 파일 안에 존재합니다.\n- CPython 컴파일러가 [future 구문](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements)과 마주칠 때, 먼저 `future.c`에서 적절한 코드를 실행한 후 그걸 일반적인 구문으로 간주합니다.\n\n---\n\n### ▶ 평생 친근한 아저씨 같은 언어를 만나봅시다\n\n\u003c!-- Example ID: 6427fae6-e959-462d-85da-ce4c94ce41be ---\u003e\n\n**출력 결과 (Python 3.x)**\n\n```py\n\u003e\u003e\u003e from __future__ import barry_as_FLUFL\n\u003e\u003e\u003e \"Ruby\" != \"Python\" # 이건 의심할 여지가 없습니다\n  File \"some_file.py\", line 1\n    \"Ruby\" != \"Python\"\n              ^\nSyntaxError: invalid syntax\n\n\u003e\u003e\u003e \"Ruby\" \u003c\u003e \"Python\"\nTrue\n```\n\n또 시작이군.\n\n#### 💡 설명:\n\n- 이것은 2009년 4월 1일에 출시된 [PEP-401](https://www.python.org/dev/peps/pep-0401/) 와 관련이 있습니다. (이제 여러분은 무엇을 의미하는지 알 것입니다)\n- PEP-401의 일부를 인용하면\n\n  \u003e 파이선 3.0의 != 비항등 연산자는 손가락의 고통을 유발하는 끔직한 실수라는 것을 인지하고, FLUFL은 유일한 문법으로 \u003c\u003e 다이아몬드 연산자를 복구시켰습니다.\n\n- 베리 아저씨가 PEP에서 공유한 것들은 더 많은데, [여기](https://www.python.org/dev/peps/pep-0401/) 서 읽을 수 있습니다.\n- 이것은 대화형 환경에서는 잘 작동하지만, 파이썬 파일을 통해서는 `SyntaxError`를 일으킵니다. ([이 이슈](https://github.com/satwikkansal/wtfpython/issues/94)를 읽어보세요) 하지만, 여러분이 구분을 `eval`이나 `compile`으로 감싼다면 잘 작동할 것입니다.\n  ```py\n  from __future__ import barry_as_FLUFL\n  print(eval('\"Ruby\" \u003c\u003e \"Python\"'))\n  ```\n\n---\n\n### ▶ 파이썬 조차 사랑이 복잡하다는 것을 이해합니다\n\n\u003c!-- Example ID: b93cad9e-d341-45d1-999c-fcdce65bed25 ---\u003e\n\n```py\nimport this\n```\n\n잠깐, **this**가 뭔가요? `this`는 사랑입니다 :heart:\n\n**출력 결과:**\n\n```\nThe Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbuttercrab%2Fwtfpython-ko","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbuttercrab%2Fwtfpython-ko","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbuttercrab%2Fwtfpython-ko/lists"}