FAQdash

Python FAQ 질문 집합

116 개 고유 영어 제목. 고정 파일 세 개의 내용이며 수요 지표가 아닙니다.

첫 일치 질문

Is there a source code-level debugger with breakpoints and single-stepping?

65 개 고유 질문 일치. 필터 초기화

원문 파일별 질문 수

원문 파일별 고유 질문 수옆 표와 같은 수치입니다. 필터 결과만 집계합니다.일반0프로그래밍65설계와 역사0

차트 수치

분모: 65 개 일치 고유 질문
파일질문 수%
일반00.0
프로그래밍65100.0
설계와 역사00.0

제목 하나를 질문 하나로 셉니다. 추론한 의도가 아니라 원문 파일로 분류합니다. 아래 각 질문에 원문 출현 건수를 표시합니다.

질문과 원문 출현 건수

RST 표기를 포함한 영어 원문 제목을 보존했습니다. 건수는 이 스냅샷에 한정됩니다. 답변 맥락은 원문에서 확인하세요.

프로그래밍 / 65 개 일치 질문

보관 영어 RST 전체 / PSF License v2

보관 첫 지면 전체 화면 보기 (이 질문의 화면 아님, 로컬 뷰어) / 이미지 출처

Is there a source code-level debugger with breakpoints and single-stepping?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L15-15
보관 원문 맥락 읽기

영어 원문 발췌, 줄 15-27. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Is there a source code-level debugger with breakpoints and single-stepping?
---------------------------------------------------------------------------

Yes.

Several debuggers for Python are described below, and the built-in function
:func:`breakpoint` allows you to drop into any of them.

The pdb module is a simple but adequate console-mode debugger for Python. It is
part of the standard Python library, and is :mod:`documented in the Library
Reference Manual <pdb>`. You can also write your own debugger by using the code
for pdb as an example.

Are there tools to help find bugs or perform static analysis?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L54-54
보관 원문 맥락 읽기

영어 원문 발췌, 줄 54-66. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Are there tools to help find bugs or perform static analysis?
-------------------------------------------------------------

Yes.

`Ruff <https://docs.astral.sh/ruff/>`__,
`Pylint <https://pylint.readthedocs.io/>`__ and
`Pyflakes <https://github.com/PyCQA/pyflakes>`__ do basic checking that will
help you catch bugs sooner.

Static type checkers such as `mypy <https://mypy-lang.org/>`__,
`ty <https://docs.astral.sh/ty/>`__,
`Pyrefly <https://pyrefly.org/>`__, and

How can I create a stand-alone binary from a Python script?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L73-73
보관 원문 맥락 읽기

영어 원문 발췌, 줄 73-85. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How can I create a stand-alone binary from a Python script?
-----------------------------------------------------------

You don't need the ability to compile Python to C code if all you want is a
stand-alone program that users can download and run without having to install
the Python distribution first.  There are a number of tools that determine the
set of modules required by a program and bind these modules together with a
Python binary to produce a single executable.

One is to use the freeze tool, which is included in the Python source tree as
:source:`Tools/freeze`.
It converts Python byte code to C arrays; with a C compiler you can
embed all your modules into a new program, which is then linked with the

Are there coding standards or a style guide for Python programs?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L108-108
보관 원문 맥락 읽기

영어 원문 발췌, 줄 108-120. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Are there coding standards or a style guide for Python programs?
----------------------------------------------------------------

Yes.  The coding style required for standard library modules is documented as
:pep:`8`.


Core language
=============

.. _faq-unboundlocalerror:

Why am I getting an UnboundLocalError when the variable has a value?

Why am I getting an UnboundLocalError when the variable has a value?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L120-120
보관 원문 맥락 읽기

영어 원문 발췌, 줄 120-132. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Why am I getting an UnboundLocalError when the variable has a value?
--------------------------------------------------------------------

It can be a surprise to get the :exc:`UnboundLocalError` in previously working
code when it is modified by adding an assignment statement somewhere in
the body of a function.

This code:

   >>> x = 10
   >>> def bar():
   ...     print(x)
   ...

What are the rules for local and global variables in Python?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L193-193
보관 원문 맥락 읽기

영어 원문 발췌, 줄 193-205. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What are the rules for local and global variables in Python?
------------------------------------------------------------

In Python, variables that are only referenced inside a function are implicitly
global.  If a variable is assigned a value anywhere within the function's body,
it's assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment's consideration explains this.  On
one hand, requiring :keyword:`global` for assigned variables provides a bar
against unintended side-effects.  On the other hand, if ``global`` was required
for all global references, you'd be using ``global`` all the time.  You'd have
to declare as global every reference to a built-in function or to a component of
an imported module.  This clutter would defeat the usefulness of the ``global``

Why do lambdas defined in a loop with different values all return the same result?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L209-209
보관 원문 맥락 읽기

영어 원문 발췌, 줄 209-221. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Why do lambdas defined in a loop with different values all return the same result?
----------------------------------------------------------------------------------

Assume you use a for loop to define a few different lambdas (or even plain
functions), for example::

   >>> squares = []
   >>> for x in range(5):
   ...     squares.append(lambda: x**2)

This gives you a list that contains 5 lambdas that calculate ``x**2``.  You
might expect that, when called, they would return, respectively, ``0``, ``1``,
``4``, ``9``, and ``16``.  However, when you actually try you will see that

How do I share global variables across modules?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L261-261
보관 원문 맥락 읽기

영어 원문 발췌, 줄 261-273. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I share global variables across modules?
------------------------------------------------

The canonical way to share information across modules within a single program is
to create a special module (often called config or cfg).  Just import the config
module in all modules of your application; the module then becomes available as
a global name.  Because there is only one instance of each module, any changes
made to the module object get reflected everywhere.  For example:

config.py::

   x = 0   # Default value of the 'x' configuration setting

What are the "best practices" for using import in a module?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L289-289
보관 원문 맥락 읽기

영어 원문 발췌, 줄 289-301. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What are the "best practices" for using import in a module?
-----------------------------------------------------------

In general, don't use ``from modulename import *``.  Doing so clutters the
importer's namespace, and makes it much harder for linters to detect undefined
names.

Import modules at the top of a file.  Doing so makes it clear what other modules
your code requires and avoids questions of whether the module name is in scope.
Using one import per line makes it easy to add and delete module imports, but
using multiple imports per line uses less screen space.

It's good practice if you import modules in the following order:

Why are default values shared between objects?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L339-339
보관 원문 맥락 읽기

영어 원문 발췌, 줄 339-351. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Why are default values shared between objects?
----------------------------------------------

This type of bug commonly bites neophyte programmers.  Consider this function::

   def foo(mydict={}):  # Danger: shared reference to one dict for all calls
       ... compute something ...
       mydict[key] = value
       return mydict

The first time you call this function, ``mydict`` contains a single item.  The
second time, ``mydict`` contains two items because when ``foo()`` begins
executing, ``mydict`` starts out with an item already in it.

How can I pass optional or keyword parameters from one function to another?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L395-395
보관 원문 맥락 읽기

영어 원문 발췌, 줄 395-407. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How can I pass optional or keyword parameters from one function to another?
---------------------------------------------------------------------------

Collect the arguments using the ``*`` and ``**`` specifiers in the function's
parameter list; this gives you the positional arguments as a tuple and the
keyword arguments as a dictionary.  You can then pass these arguments when
calling another function by using ``*`` and ``**``::

   def f(x, *args, **kwargs):
       ...
       kwargs['width'] = '14.3c'
       ...
       g(x, *args, **kwargs)

What is the difference between arguments and parameters?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L416-416
보관 원문 맥락 읽기

영어 원문 발췌, 줄 416-428. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What is the difference between arguments and parameters?
--------------------------------------------------------

:term:`Parameters <parameter>` are defined by the names that appear in a
function definition, whereas :term:`arguments <argument>` are the values
actually passed to a function when calling it.  Parameters define what
:term:`kind of arguments <parameter>` a function can accept.  For
example, given the function definition::

   def func(foo, bar=None, **kwargs):
       pass

*foo*, *bar* and *kwargs* are parameters of ``func``.  However, when calling

Why did changing list 'y' also change list 'x'?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L436-436
보관 원문 맥락 읽기

영어 원문 발췌, 줄 436-448. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Why did changing list 'y' also change list 'x'?
------------------------------------------------

If you wrote code like::

   >>> x = []
   >>> y = x
   >>> y.append(10)
   >>> y
   [10]
   >>> x
   [10]

How do I write a function with output parameters (call by reference)?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L511-511
보관 원문 맥락 읽기

영어 원문 발췌, 줄 511-523. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I write a function with output parameters (call by reference)?
---------------------------------------------------------------------

Remember that arguments are passed by assignment in Python.  Since assignment
just creates references to objects, there's no alias between an argument name in
the caller and callee, and consequently no call-by-reference.  You can achieve the
desired effect in a number of ways.

1) By returning a tuple of the results::

      >>> def func1(a, b):
      ...     a = 'new-value'        # a and b are local names
      ...     b = b + 1              # assigned to new objects

How do you make a higher order function in Python?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L578-578
보관 원문 맥락 읽기

영어 원문 발췌, 줄 578-590. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do you make a higher order function in Python?
--------------------------------------------------

You have two choices: you can use nested scopes or you can use callable objects.
For example, suppose you wanted to define ``linear(a,b)`` which returns a
function ``f(x)`` that computes the value ``a*x+b``.  Using nested scopes::

   def linear(a, b):
       def result(x):
           return a * x + b
       return result

Or using a callable object::

How do I copy an object in Python?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L637-637
보관 원문 맥락 읽기

영어 원문 발췌, 줄 637-649. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I copy an object in Python?
----------------------------------

In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
Not all objects can be copied, but most can.

Some objects can be copied more easily.  Dictionaries have a :meth:`~dict.copy`
method::

   newdict = olddict.copy()

Sequences can be copied by slicing::

How can I find the methods or attributes of an object?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L653-653
보관 원문 맥락 읽기

영어 원문 발췌, 줄 653-665. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How can I find the methods or attributes of an object?
------------------------------------------------------

For an instance ``x`` of a user-defined class, :func:`dir(x) <dir>` returns an alphabetized
list of the names containing the instance attributes and methods and attributes
defined by its class.


How can my code discover the name of an object?
-----------------------------------------------

Generally speaking, it can't, because objects don't really have names.
Essentially, assignment always binds a name to a value; the same is true of

How can my code discover the name of an object?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L661-661
보관 원문 맥락 읽기

영어 원문 발췌, 줄 661-673. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How can my code discover the name of an object?
-----------------------------------------------

Generally speaking, it can't, because objects don't really have names.
Essentially, assignment always binds a name to a value; the same is true of
``def`` and ``class`` statements, but in that case the value is a
callable. Consider the following code::

   >>> class A:
   ...     pass
   ...
   >>> B = A
   >>> a = B()

What's up with the comma operator's precedence?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L702-702
보관 원문 맥락 읽기

영어 원문 발췌, 줄 702-714. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What's up with the comma operator's precedence?
-----------------------------------------------

Comma is not an operator in Python.  Consider this session::

    >>> "a" in "b", "a"
    (False, 'a')

Since the comma is not an operator, but a separator between expressions the
above is evaluated as if you had entered::

    ("a" in "b"), "a"

Is there an equivalent of C's "?:" ternary operator?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L723-723
보관 원문 맥락 읽기

영어 원문 발췌, 줄 723-735. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Is there an equivalent of C's "?:" ternary operator?
----------------------------------------------------

Yes, there is. The syntax is as follows::

   [on_true] if [expression] else [on_false]

   x, y = 50, 25
   small = x if x < y else y

Before this syntax was introduced in Python 2.5, a common idiom was to use
logical operators::

Is it possible to write obfuscated one-liners in Python?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L743-743
보관 원문 맥락 읽기

영어 원문 발췌, 줄 743-755. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Is it possible to write obfuscated one-liners in Python?
--------------------------------------------------------

Yes.  Usually this is done by nesting :keyword:`lambda` within
:keyword:`!lambda`.  See the following three examples, slightly adapted from Ulf Bartelt::

   from functools import reduce

   # Primes < 1000
   print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
   map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))

   # First 10 Fibonacci numbers

What does the slash(/) in the parameter list of a function mean?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L778-778
보관 원문 맥락 읽기

영어 원문 발췌, 줄 778-790. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What does the slash(/) in the parameter list of a function mean?
----------------------------------------------------------------

A slash in the argument list of a function denotes that the parameters prior to
it are positional-only.  Positional-only parameters are the ones without an
externally usable name.  Upon calling a function that accepts positional-only
parameters, arguments are mapped to parameters based solely on their position.
For example, :func:`divmod` is a function that accepts positional-only
parameters. Its documentation looks like this::

   >>> help(divmod)
   Help on built-in function divmod in module builtins:

How do I specify hexadecimal and octal integers?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L807-807
보관 원문 맥락 읽기

영어 원문 발췌, 줄 807-819. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I specify hexadecimal and octal integers?
------------------------------------------------

To specify an octal digit, precede the octal value with a zero, and then a lower
or uppercase "o".  For example, to set the variable "a" to the octal value "10"
(8 in decimal), type::

   >>> a = 0o10
   >>> a
   8

Hexadecimal is just as easy.  Simply precede the hexadecimal number with a zero,
and then a lower or uppercase "x".  Hexadecimal digits can be specified in lower

Why does -22 // 10 return -3?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L830-830
보관 원문 맥락 읽기

영어 원문 발췌, 줄 830-842. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Why does -22 // 10 return -3?
-----------------------------

It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
If you want that, and also want::

    i == (i // j) * j + (i % j)

then integer division has to return the floor.  C also requires that identity to
hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
the same sign as ``i``.

There are few real use cases for ``i % j`` when ``j`` is negative.  When ``j``

How do I get int literal attribute instead of SyntaxError?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L849-849
보관 원문 맥락 읽기

영어 원문 발췌, 줄 849-861. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I get int literal attribute instead of SyntaxError?
----------------------------------------------------------

Trying to lookup an ``int`` literal attribute in the normal manner gives
a :exc:`SyntaxError` because the period is seen as a decimal point::

   >>> 1.__class__
     File "<stdin>", line 1
     1.__class__
      ^
   SyntaxError: invalid decimal literal

The solution is to separate the literal from the period

How do I convert a string to a number?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L870-870
보관 원문 맥락 읽기

영어 원문 발췌, 줄 870-882. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I convert a string to a number?
--------------------------------------

For integers, use the built-in :func:`int` type constructor, for example, ``int('144')
== 144``.  Similarly, :func:`float` converts to a floating-point number,
for example, ``float('144') == 144.0``.

By default, these interpret the number as decimal, so that ``int('0144') ==
144`` holds true, and ``int('0x144')`` raises :exc:`ValueError`. ``int(string,
base)`` takes the base to convert from as a second optional argument, so ``int(
'0x144', 16) == 324``.  If the base is specified as 0, the number is interpreted
using Python's rules: a leading '0o' indicates octal, and '0x' indicates a hex
number.

How do I convert a number to a string?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L896-896
보관 원문 맥락 읽기

영어 원문 발췌, 줄 896-908. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I convert a number to a string?
--------------------------------------

For example, to convert the number ``144`` to the string ``'144'``, use the built-in type
constructor :func:`str`.  If you want a hexadecimal or octal representation, use
the built-in functions :func:`hex` or :func:`oct`.  For fancy formatting, see
the :ref:`f-strings` and :ref:`formatstrings` sections.
For example, ``"{:04d}".format(144)`` yields
``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.


How do I modify a string in place?
----------------------------------

How do I modify a string in place?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L907-907
보관 원문 맥락 읽기

영어 원문 발췌, 줄 907-919. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I modify a string in place?
----------------------------------

You can't, because strings are immutable.  In most situations, you should
simply construct a new string from the various parts you want to assemble
it from.  However, if you need an object with the ability to modify in-place
Unicode data, try using an :class:`io.StringIO` object or the :mod:`array`
module::

   >>> import io
   >>> s = "Hello, world"
   >>> sio = io.StringIO(s)
   >>> sio.getvalue()

How do I use strings to call functions/methods?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L939-939
보관 원문 맥락 읽기

영어 원문 발췌, 줄 939-951. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I use strings to call functions/methods?
-----------------------------------------------

There are various techniques.

* The best is to use a dictionary that maps strings to functions.  The primary
  advantage of this technique is that the strings do not need to match the names
  of the functions.  This is also the primary technique used to emulate a case
  construct::

     def a():
         pass

Is there an equivalent to Perl's ``chomp()`` for removing trailing newlines from strings?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L991-991
보관 원문 맥락 읽기

영어 원문 발췌, 줄 991-1003. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Is there an equivalent to Perl's ``chomp()`` for removing trailing newlines from strings?
-----------------------------------------------------------------------------------------

You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
terminator from the end of the string ``S`` without removing other trailing
whitespace.  If the string ``S`` represents more than one line, with several
empty lines at the end, the line terminators for all the blank lines will
be removed::

   >>> lines = ("line 1 \r\n"
   ...          "\r\n"
   ...          "\r\n")
   >>> lines.rstrip("\n\r")

Is there a ``scanf()`` or ``sscanf()`` equivalent?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1010-1010
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1010-1022. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Is there a ``scanf()`` or ``sscanf()`` equivalent?
--------------------------------------------------

Not as such.

For simple input parsing, the easiest approach is usually to split the line into
whitespace-delimited words using the :meth:`~str.split` method of string objects
and then convert decimal strings to numeric values using :func:`int` or
:func:`float`.  :meth:`!split` supports an optional "sep" parameter which is useful
if the line uses something other than whitespace as a separator.

For more complicated input parsing, regular expressions are more powerful
than C's ``sscanf`` and better suited for the task.

What does ``UnicodeDecodeError`` or ``UnicodeEncodeError`` error mean?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1025-1025
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1025-1037. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What does ``UnicodeDecodeError`` or ``UnicodeEncodeError`` error mean?
----------------------------------------------------------------------

See the :ref:`unicode-howto`.


.. _faq-programming-raw-string-backslash:

Can I end a raw string with an odd number of backslashes?
---------------------------------------------------------

A raw string ending with an odd number of backslashes will escape the string's quote::

Can I end a raw string with an odd number of backslashes?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1033-1033
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1033-1045. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Can I end a raw string with an odd number of backslashes?
---------------------------------------------------------

A raw string ending with an odd number of backslashes will escape the string's quote::

   >>> r'C:\this\will\not\work\'
     File "<stdin>", line 1
       r'C:\this\will\not\work\'
       ^
   SyntaxError: unterminated string literal (detected at line 1)

There are several workarounds for this. One is to use regular strings and double
the backslashes::

My program is too slow. How do I speed it up?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1075-1075
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1075-1087. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

My program is too slow. How do I speed it up?
---------------------------------------------

That's a tough one, in general.  First, here is a list of things to
remember before diving further:

* Performance characteristics vary across Python implementations.  This FAQ
  focuses on :term:`CPython`.
* Behaviour can vary across operating systems, especially when talking about
  I/O or multi-threading.
* You should always find the hot spots in your program *before* attempting to
  optimize any code (see the :mod:`profile` module).
* Writing benchmark scripts will allow you to iterate quickly when searching

What is the most efficient way to concatenate many strings together?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1134-1134
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1134-1146. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What is the most efficient way to concatenate many strings together?
--------------------------------------------------------------------

:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
many strings together is inefficient as each concatenation creates a new
object.  In the general case, the total runtime cost is quadratic in the
total string length.  See :ref:`time-complexity` for more information.

To accumulate many :class:`str` objects, the recommended idiom is to place
them into a list and call :meth:`str.join` at the end::

   chunks = []
   for s in my_strings:

How do I convert between tuples and lists?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1163-1163
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1163-1175. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I convert between tuples and lists?
------------------------------------------

The type constructor ``tuple(seq)`` converts any sequence (actually, any
iterable) into a tuple with the same items in the same order.

For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
yields ``('a', 'b', 'c')``.  If the argument is a tuple, it does not make a copy
but returns the same object, so it is cheap to call :func:`tuple` when you
aren't sure that an object is already a tuple.

The type constructor ``list(seq)`` converts any sequence or iterable into a list
with the same items in the same order.  For example, ``list((1, 2, 3))`` yields

What's a negative index?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1180-1180
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1180-1192. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What's a negative index?
------------------------

Python sequences are indexed with positive numbers and negative numbers.  For
positive numbers 0 is the first index 1 is the second index and so forth.  For
negative indices -1 is the last index and -2 is the penultimate (next to last)
index and so forth.  Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.

Using negative indices can be very convenient.  For example ``S[:-1]`` is all of
the string except for its last character, which is useful for removing the
trailing newline from a string.

How do I iterate over a sequence in reverse order?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1193-1193
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1193-1205. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I iterate over a sequence in reverse order?
--------------------------------------------------

Use the :func:`reversed` built-in function::

   for x in reversed(sequence):
       ...  # do something with x ...

This returns a reverse iterator without modifying your original sequence.


How do you remove duplicates from a list?
-----------------------------------------

How do you remove duplicates from a list?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1204-1204
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1204-1216. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do you remove duplicates from a list?
-----------------------------------------

See the Python Cookbook for a long discussion of many ways to do this:

   https://code.activestate.com/recipes/52560/

If you don't mind reordering the list, sort it and then scan from the end of the
list, deleting duplicates as you go::

   if mylist:
       mylist.sort()
       last = mylist[-1]

How do you remove multiple items from a list?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1232-1232
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1232-1244. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do you remove multiple items from a list?
---------------------------------------------

As with removing duplicates, explicitly iterating in reverse with a
delete condition is one possibility.  However, it is easier and faster
to use slice replacement with an implicit or explicit forward iteration.
Here are three variations::

   mylist[:] = filter(keep_function, mylist)
   mylist[:] = (x for x in mylist if keep_condition)
   mylist[:] = [x for x in mylist if keep_condition]

The list comprehension may be fastest.

How do you make an array in Python?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1247-1247
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1247-1259. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do you make an array in Python?
-----------------------------------

Use a list::

   ["this", 1, "is", "an", "array"]

Lists are equivalent to C or Pascal arrays in their time complexity; the primary
difference is that a Python list can contain objects of many different types.

The ``array`` module also provides methods for creating arrays of fixed types
with compact representations, but they are slower to index than lists.  Also
note that `NumPy <https://numpy.org/>`_

How do I create a multidimensional list?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1275-1275
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1275-1287. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I create a multidimensional list?
----------------------------------------

You probably tried to make a multidimensional array like this::

   >>> A = [[None] * 2] * 3

This looks correct if you print it:

.. testsetup::

   A = [[None] * 2] * 3

How do I apply a method or function to a sequence of objects?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1327-1327
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1327-1339. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I apply a method or function to a sequence of objects?
-------------------------------------------------------------

To call a method or function and accumulate the return values in a list,
a :term:`list comprehension` is an elegant solution::

   result = [obj.method() for obj in mylist]

   result = [function(obj) for obj in mylist]

To just run the method or function without saving the return values,
a plain :keyword:`for` loop will suffice::

Why does a_tuple[i] += ['item'] raise an exception when the addition works?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1349-1349
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1349-1361. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Why does a_tuple[i] += ['item'] raise an exception when the addition works?
---------------------------------------------------------------------------

This is because of a combination of the fact that augmented assignment
operators are *assignment* operators, and the difference between mutable and
immutable objects in Python.

This discussion applies in general when augmented assignment operators are
applied to elements of a tuple that point to mutable objects, but we'll use
a ``list`` and ``+=`` as our exemplar.

If you wrote::

I want to do a complicated sort: can you do a Schwartzian Transform in Python?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1436-1436
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1436-1448. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

I want to do a complicated sort: can you do a Schwartzian Transform in Python?
------------------------------------------------------------------------------

The technique, attributed to Randal Schwartz of the Perl community, sorts the
elements of a list by a metric which maps each element to its "sort value". In
Python, use the ``key`` argument for the :meth:`list.sort` method::

   Isorted = L[:]
   Isorted.sort(key=lambda s: int(s[10:15]))


How can I sort one list by values from another list?
----------------------------------------------------

How can I sort one list by values from another list?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1447-1447
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1447-1459. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How can I sort one list by values from another list?
----------------------------------------------------

Merge them into an iterator of tuples, sort the resulting list, and then pick
out the element you want.

   >>> list1 = ["what", "I'm", "sorting", "by"]
   >>> list2 = ["something", "else", "to", "sort"]
   >>> pairs = zip(list1, list2)
   >>> pairs = sorted(pairs)
   >>> pairs
   [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
   >>> result = [x[1] for x in pairs]

What is a class?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1467-1467
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1467-1479. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What is a class?
----------------

A class is the particular object type created by executing a class statement.
Class objects are used as templates to create instance objects, which embody
both the data (attributes) and code (methods) specific to a datatype.

A class can be based on one or more other classes, called its base class(es). It
then inherits the attributes and methods of its base classes. This allows an
object model to be successively refined by inheritance.  You might have a
generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
that handle various specific mailbox formats.

What is a method?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1482-1482
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1482-1494. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What is a method?
-----------------

A method is a function on some object ``x`` that you normally call as
``x.name(arguments...)``.  Methods are defined as functions inside the class
definition::

   class C:
       def meth(self, arg):
           return arg * 2 + self.attribute


What is self?

What is self?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1494-1494
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1494-1506. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What is self?
-------------

Self is merely a conventional name for the first argument of a method.  A method
defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
some instance ``x`` of the class in which the definition occurs; the called
method will think it is called as ``meth(x, a, b, c)``.

See also :ref:`why-self`.


How do I check if an object is an instance of a given class or of a subclass of it?
-----------------------------------------------------------------------------------

How do I check if an object is an instance of a given class or of a subclass of it?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1505-1505
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1505-1517. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I check if an object is an instance of a given class or of a subclass of it?
-----------------------------------------------------------------------------------

Use the built-in function :func:`isinstance(obj, cls) <isinstance>`.  You can
check if an object
is an instance of any of a number of classes by providing a tuple instead of a
single class, for example, ``isinstance(obj, (class1, class2, ...))``, and can also
check whether an object is one of Python's built-in types, for example,
``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.

Note that :func:`isinstance` also checks for virtual inheritance from an
:term:`abstract base class`.  So, the test will return ``True`` for a
registered class even if hasn't directly or indirectly inherited from it.  To

What is delegation?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1579-1579
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1579-1591. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

What is delegation?
-------------------

Delegation is an object-oriented technique (also called a design pattern).
Let's say you have an object ``x`` and want to change the behaviour of just one
of its methods.  You can create a new class that provides a new implementation
of the method you're interested in changing and delegates all other methods to
the corresponding method of ``x``.

Python programmers can easily implement delegation.  For example, the following
class implements a class that behaves like a file but converts all written data
to uppercase::

How do I call a method defined in a base class from a derived class that extends it?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1633-1633
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1633-1645. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I call a method defined in a base class from a derived class that extends it?
------------------------------------------------------------------------------------

Use the built-in :func:`super` function::

   class Derived(Base):
       def meth(self):
           super().meth()  # calls Base.meth

In the example, :func:`super` will automatically determine the instance from
which it was called (the ``self`` value), look up the :term:`method resolution
order` (MRO) with ``type(self).__mro__``, and return a proxy that searches for
methods starting with the next class after ``Derived`` in the MRO: ``Base``.

How can I organize my code to make it easier to change the base class?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1648-1648
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1648-1660. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How can I organize my code to make it easier to change the base class?
----------------------------------------------------------------------

You could assign the base class to an alias and derive from the alias.  Then all
you have to change is the value assigned to the alias.  Incidentally, this trick
is also handy if you want to decide dynamically (such as depending on availability
of resources) which base class to use.  Example::

   class Base:
       ...

   BaseAlias = Base

How do I create static class data and static class methods?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1665-1665
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1665-1677. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I create static class data and static class methods?
-----------------------------------------------------------

Both static data and static methods (in the sense of C++ or Java) are supported
in Python.

For static data, simply define a class attribute.  To assign a new value to the
attribute, you have to explicitly use the class name in the assignment::

   class C:
       count = 0   # number of times C.__init__ called

       def __init__(self):

How can I overload constructors (or methods) in Python?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1712-1712
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1712-1724. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How can I overload constructors (or methods) in Python?
-------------------------------------------------------

This answer actually applies to all methods, but the question usually comes up
first in the context of constructors.

In C++ you'd write:

.. code-block:: c++

    class C {
        C() { cout << "No arguments\n"; }
        C(int i) { cout << "Argument is " << i << "\n"; }

How do I get a list of all instances of a given class?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1827-1827
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1827-1839. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I get a list of all instances of a given class?
------------------------------------------------------

Python does not keep track of all instances of a class (or of a built-in type).
You can program the class's constructor to keep track of all instances by
keeping a list of weak references to each instance.


Why does the result of ``id()`` appear to be not unique?
--------------------------------------------------------

The :func:`id` builtin returns an integer that is guaranteed to be unique during
the lifetime of the object.  Since in CPython, this is the object's memory

Why does the result of ``id()`` appear to be not unique?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1835-1835
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1835-1847. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

Why does the result of ``id()`` appear to be not unique?
--------------------------------------------------------

The :func:`id` builtin returns an integer that is guaranteed to be unique during
the lifetime of the object.  Since in CPython, this is the object's memory
address, it happens frequently that after an object is deleted from memory, the
next freshly created object is allocated at the same position in memory.  This
is illustrated by this example:

>>> id(1000) # doctest: +SKIP
13901272
>>> id(2000) # doctest: +SKIP
13901272

When can I rely on identity tests with the *is* operator?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1863-1863
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1863-1875. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

When can I rely on identity tests with the *is* operator?
---------------------------------------------------------

The ``is`` operator tests for object identity.  The test ``a is b`` is
equivalent to ``id(a) == id(b)``.

The most important property of an identity test is that an object is always
identical to itself, ``a is a`` always returns ``True``.  Identity tests are
usually faster than equality tests.  And unlike equality tests, identity tests
are guaranteed to return a boolean ``True`` or ``False``.

However, identity tests can *only* be substituted for equality tests when
object identity is assured.  Generally, there are three circumstances where

How can a subclass control what data is stored in an immutable instance?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L1952-1952
보관 원문 맥락 읽기

영어 원문 발췌, 줄 1952-1964. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How can a subclass control what data is stored in an immutable instance?
------------------------------------------------------------------------

When subclassing an immutable type, override the :meth:`~object.__new__` method
instead of the :meth:`~object.__init__` method.  The latter only runs *after* an
instance is created, which is too late to alter data in an immutable
instance.

All of these immutable classes have a different signature than their
parent class:

.. testcode::

How do I cache method calls?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L2002-2002
보관 원문 맥락 읽기

영어 원문 발췌, 줄 2002-2014. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I cache method calls?
----------------------------

The two principal tools for caching methods are
:deco:`functools.cached_property` and :deco:`functools.lru_cache`.  The
former stores results at the instance level and the latter at the class
level.

The ``cached_property`` approach only works with methods that do not take
any arguments.  It does not create a reference to the instance.  The
cached method result will be kept only as long as the instance is alive.

The advantage is that when an instance is no longer used, the cached

How do I create a .pyc file?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L2061-2061
보관 원문 맥락 읽기

영어 원문 발췌, 줄 2061-2073. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I create a .pyc file?
----------------------------

When a module is imported for the first time (or when the source file has
changed since the current compiled file was created) a ``.pyc`` file containing
the compiled code should be created in a ``__pycache__`` subdirectory of the
directory containing the ``.py`` file.  The ``.pyc`` file will have a
filename that starts with the same name as the ``.py`` file, and ends with
``.pyc``, with a middle component that depends on the particular ``python``
binary that created it.  (See :pep:`3147` for details.)

One reason that a ``.pyc`` file may not be created is a permissions problem
with the directory containing the source file, meaning that the ``__pycache__``

How do I find the current module name?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L2111-2111
보관 원문 맥락 읽기

영어 원문 발췌, 줄 2111-2123. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How do I find the current module name?
--------------------------------------

A module can find out its own module name by looking at the predefined global
variable ``__name__``.  If this has the value ``'__main__'``, the program is
running as a script.  Many modules that are usually used by importing them also
provide a command-line interface or a self-test, and only execute this code
after checking ``__name__``::

   def main():
       print('Running test...')
       ...

How can I have modules that mutually import each other?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L2128-2128
보관 원문 맥락 읽기

영어 원문 발췌, 줄 2128-2140. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

How can I have modules that mutually import each other?
-------------------------------------------------------

Suppose you have the following modules:

:file:`foo.py`::

   from bar import bar_var
   foo_var = 1

:file:`bar.py`::

   from foo import foo_var

__import__('x.y.z') returns <module 'x'>; how do I get z?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L2183-2183
보관 원문 맥락 읽기

영어 원문 발췌, 줄 2183-2195. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

__import__('x.y.z') returns <module 'x'>; how do I get z?
---------------------------------------------------------

Consider using the convenience function :func:`~importlib.import_module` from
:mod:`importlib` instead::

   z = importlib.import_module('x.y.z')


When I edit an imported module and reimport it, the changes don't show up.  Why does this happen?
-------------------------------------------------------------------------------------------------

For reasons of efficiency as well as consistency, Python only reads the module

When I edit an imported module and reimport it, the changes don't show up. Why does this happen?

원문 출현 건수: 1 / 질문 고정 링크

[2] programming.rst L2192-2192
보관 원문 맥락 읽기

영어 원문 발췌, 줄 2192-2204. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.

When I edit an imported module and reimport it, the changes don't show up.  Why does this happen?
-------------------------------------------------------------------------------------------------

For reasons of efficiency as well as consistency, Python only reads the module
file on the first time a module is imported.  If it didn't, in a program
consisting of many modules where each one imports the same basic module, the
basic module would be parsed and re-parsed many times.  To force re-reading of a
changed module, do this::

   import importlib
   import modname
   importlib.reload(modname)
원문 파일 세 개와 예시 질문
원문 파일, 바이트 해시와 JSON
  1. [1] Doc/faq/general.rst

    보관 원본 바이트

    SHA256 032069d738fc8ef2cc907e1d79e2b19898978dab722cd30c108684a29cd1cf0e

  2. [2] Doc/faq/programming.rst

    보관 원본 바이트

    SHA256 4a0bc1b572f4772afd47938cb08a39e857907f2cf26f045323c17a0db7b3f39e

  3. [3] Doc/faq/design.rst

    보관 원본 바이트

    SHA256 65ba1d14ad1f245ff177a1a7758b77880e76a9d37337b577619fdebe65f083e6

  4. [4] LICENSE

    보관 원본 바이트

    SHA256 b0e25a78cffb43f4d92de8b61ccfa1f1f98ecbc22330b54b5251e7b6ba010231

추출 JSON 전체