itemId
stringlengths
1
34
itemType
stringclasses
4 values
site
stringclasses
4 values
scrapedAt
timestamp[s]date
2026-08-03 00:21:25
2026-08-03 04:01:45
tagName
stringlengths
1
34
questionCount
int64
2
2.53M
hasSynonyms
bool
2 classes
isModeratorOnly
bool
1 class
isRequired
bool
1 class
link
stringlengths
32
258
_run_id
stringclasses
57 values
_dataset_id
stringclasses
57 values
questionId
int64
1
80M
title
stringlengths
15
150
score
int64
-10
35.3k
viewCount
int64
6
16.7M
answerCount
int64
0
296
isAnswered
bool
2 classes
hasAcceptedAnswer
bool
2 classes
tags
listlengths
1
6
createdAt
timestamp[s]date
2008-08-01 04:18:04
2026-08-03 03:37:34
lastActivityAt
timestamp[s]date
2008-10-30 09:20:18
2026-08-03 01:36:51
ownerDisplayName
stringlengths
3
30
isClosed
bool
2 classes
contentLicense
stringclasses
3 values
acceptedAnswerId
int64
4
80M
ownerUserId
int64
1
33M
ownerReputation
int64
1
1.53M
userId
int64
13
33M
displayName
stringclasses
897 values
reputation
int64
1
1.53M
userType
stringclasses
3 values
lastAccessAt
timestamp[s]date
2011-01-10 08:55:57
2026-08-03 03:38:13
goldBadges
int64
0
895
silverBadges
int64
0
9.32k
bronzeBadges
int64
0
9.36k
reputationChangeMonth
int64
-40
1.43k
reputationChangeYear
int64
-1,146
11.7k
websiteUrl
stringclasses
302 values
location
stringclasses
279 values
acceptRate
int64
17
100
answerId
int64
1.13k
80M
isAccepted
bool
2 classes
bodyText
stringlengths
31
24.4k
bodyHtml
stringlengths
39
34.9k
answers
listlengths
1
3
answersFetched
int64
0
3
448271
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/448271/what-is-init-py-for
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
448,271
What is __init__.py for?
3,942
2,801,807
14
true
true
[ "python", "module", "package", "python-packaging" ]
2009-01-15T20:09:09
2024-10-26T06:18:34
Mat
false
CC BY-SA 4.0
448,279
42,974
87,620
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
What is __init__.py for in a Python source directory?
<p>What is <a href="https://docs.python.org/3/tutorial/modules.html#packages" rel="noreferrer"><code>__init__.py</code></a> for in a Python source directory?</p>
[ { "answerId": 448279, "score": 2116, "isAccepted": true, "createdAt": "2009-01-15T20:13:24", "ownerDisplayName": "Loki", "ownerUserId": 39057, "bodyText": "It used to be a required part of a package ( old, pre-3.3 \"regular package\" , not newer 3.3+ \"namespace package\" ). Here's the d...
1
606191
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/606191/convert-bytes-to-a-string-in-python-3
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
606,191
Convert bytes to a string in Python 3
3,887
5,412,477
23
true
true
[ "python", "string", "python-3.x" ]
2009-03-03T12:23:01
2025-01-06T01:58:20
Tomas Sedovic
false
CC BY-SA 4.0
606,199
2,239
44,783
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I captured the standard output of an external program into a bytes object: >>> from subprocess import * >>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] >>> stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' I want to convert that to a norma...
<p>I captured the standard output of an external program into a <code>bytes</code> object:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] &gt;&gt;&gt; stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thom...
[ { "answerId": 606199, "score": 5881, "isAccepted": true, "createdAt": "2009-03-03T12:26:18", "ownerDisplayName": "Aaron Maenpaa", "ownerUserId": 2603, "bodyText": "Decode the bytes object to produce a string: >>> b\"abcde\".decode(\"utf-8\") 'abcde' The above example assumes that the byt...
1
1436703
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1436703/what-is-the-difference-between-str-and-repr
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,436,703
What is the difference between __str__ and __repr__?
3,841
1,101,188
29
true
true
[ "python", "magic-methods", "repr" ]
2009-09-17T04:27:45
2025-08-07T18:37:34
Casebash
false
CC BY-SA 4.0
2,626,364
165,495
120,251
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
What is the difference between __str__ and __repr__ in Python?
<p>What is the difference between <a href="https://docs.python.org/3/reference/datamodel.html#object.__str__" rel="noreferrer"><code>__str__</code></a> and <a href="https://docs.python.org/3/reference/datamodel.html#object.__repr__" rel="noreferrer"><code>__repr__</code></a> in Python?</p>
[ { "answerId": 2626364, "score": 3633, "isAccepted": true, "createdAt": "2010-04-13T00:56:52", "ownerDisplayName": "moshez", "ownerUserId": 122683, "bodyText": "Alex Martelli summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex ’s post: The ...
1
17071871
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/17071871/how-do-i-select-rows-from-a-dataframe-based-on-column-values
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
17,071,871
How do I select rows from a DataFrame based on column values?
3,635
6,893,382
20
true
true
[ "python", "pandas", "dataframe", "indexing", "filter" ]
2013-06-12T17:42:05
2025-05-14T01:53:58
szli
false
CC BY-SA 4.0
17,071,908
458,429
39,429
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How can I select rows from a DataFrame based on values in some column in Pandas? In SQL, I would use: SELECT * FROM table WHERE column_name = some_value
<p>How can I select rows from a DataFrame based on values in some column in Pandas?</p> <p>In SQL, I would use:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM table WHERE column_name = some_value </code></pre>
[ { "answerId": 17071908, "score": 6653, "isAccepted": true, "createdAt": "2013-06-12T17:44:20", "ownerDisplayName": "unutbu", "ownerUserId": 190597, "bodyText": "To select rows whose column value equals a scalar, some_value , use == : df.loc[df['column_name'] == some_value] To select rows...
1
1024847
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1024847/how-can-i-add-new-keys-to-a-dictionary
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,024,847
How can I add new keys to a dictionary?
3,601
5,645,894
20
true
true
[ "python", "dictionary", "key", "lookup" ]
2009-06-21T22:07:39
2025-03-18T16:37:01
lfaraone
false
CC BY-SA 4.0
1,024,851
90,777
50,872
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I add a new key to an existing dictionary? It doesn't have an .add() method.
<p>How do I add a new key to an existing dictionary? It doesn't have an <code>.add()</code> method.</p>
[ { "answerId": 1024851, "score": 4464, "isAccepted": true, "createdAt": "2009-06-21T22:09:06", "ownerDisplayName": "Paolo Bergantino", "ownerUserId": 16417, "bodyText": "You create a new key/value pair on a dictionary by assigning a value to that key d = {'key': 'value'} print(d) # {'key'...
1
3437059
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
3,437,059
Does Python have a string 'contains' substring method?
3,585
7,545,827
10
true
true
[ "python", "string", "substring", "contains" ]
2010-08-09T02:52:50
2025-01-17T16:59:58
Blankman
false
CC BY-SA 3.0
3,437,070
39,677
268,914
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I'm looking for a string.contains or string.indexof method in Python. I want to do: if not somestring.contains("blah"): continue
<p>I'm looking for a <code>string.contains</code> or <code>string.indexof</code> method in Python.</p> <p>I want to do:</p> <pre><code>if not somestring.contains("blah"): continue </code></pre>
[ { "answerId": 3437070, "score": 8685, "isAccepted": true, "createdAt": "2010-08-09T02:56:21", "ownerDisplayName": "Michael Mrozek", "ownerUserId": 309308, "bodyText": "Use the in operator : if \"blah\" not in somestring: continue Note: This is case-sensitive." } ]
1
6996603
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/6996603/how-can-i-delete-a-file-or-folder-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
6,996,603
How can I delete a file or folder in Python?
3,554
4,058,628
18
true
true
[ "python", "file-io", "directory", "delete-file" ]
2011-08-09T13:05:42
2024-04-29T09:36:08
Zygimantas
false
CC BY-SA 4.0
6,996,628
854,002
35,881
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How can I delete a file or folder in Python?
<p>How can I delete a file or folder in Python?</p>
[ { "answerId": 6996628, "score": 5060, "isAccepted": true, "createdAt": "2011-08-09T13:07:39", "ownerDisplayName": "RichieHindle", "ownerUserId": 21886, "bodyText": "Use one of these methods: pathlib.Path.unlink() removes a file or symbolic link. pathlib.Path.rmdir() removes an empty dire...
1
1132941
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,132,941
"Least Astonishment" and the Mutable Default Argument
3,511
301,155
34
true
true
[ "python", "language-design", "default-parameters", "least-astonishment" ]
2009-07-15T18:00:37
2025-08-12T22:31:16
Stefano Borini
false
CC BY-SA 4.0
1,145,781
78,374
145,268
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
def foo(a=[]): a.append(5) return a Python novices expect this function called with no parameter to always return a list with only one element: [5] . The result is different and astonishing: >>> foo() [5] >>> foo() [5, 5] >>> foo() [5, 5, 5] >>> foo() [5, 5, 5, 5] >>> foo() The behavior has an underlying explanation, b...
<pre><code>def foo(a=[]): a.append(5) return a </code></pre> <p>Python novices expect this function called with no parameter to always return a list with only one element: <code>[5]</code>. The result is different and astonishing:</p> <pre><code>&gt;&gt;&gt; foo() [5] &gt;&gt;&gt; foo() [5, 5] &gt;&gt;&gt; foo...
[ { "answerId": 1145781, "score": 1963, "isAccepted": true, "createdAt": "2009-07-17T21:29:39", "ownerDisplayName": "rob", "ownerUserId": 43927, "bodyText": "Actually, this is not a design flaw, and it is not because of internals or performance. It comes simply from the fact that functions...
1
36901
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
36,901
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
3,501
1,556,482
28
true
true
[ "python", "syntax", "parameter-passing", "variadic-functions", "argument-unpacking" ]
2008-08-31T15:04:35
2026-06-03T04:41:03
Todd
false
CC BY-SA 4.0
36,908
2,572
36,380
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
What do *args and **kwargs mean in these function definitions? def foo(x, y, *args): pass def bar(x, y, **kwargs): pass See What do ** (double star/asterisk) and * (star/asterisk) mean in a function call? for the complementary question about arguments.
<p>What do <code>*args</code> and <code>**kwargs</code> mean in these function definitions?</p> <pre><code>def foo(x, y, *args): pass def bar(x, y, **kwargs): pass </code></pre> <hr /> <p><sub>See <a href="https://stackoverflow.com/questions/2921847">What do ** (double star/asterisk) and * (star/asterisk) mean...
[ { "answerId": 36908, "score": 3348, "isAccepted": true, "createdAt": "2008-08-31T15:17:31", "ownerDisplayName": "Peter Hoffmann", "ownerUserId": 720, "bodyText": "The *args and **kwargs are common idioms to allow an arbitrary number of arguments to functions, as described in the section ...
1
4906977
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/4906977/how-can-i-access-environment-variables-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
4,906,977
How can I access environment variables in Python?
3,476
3,519,584
17
true
true
[ "python", "environment-variables" ]
2011-02-05T13:03:35
2024-02-12T16:18:05
Amit Yadav
false
CC BY-SA 4.0
4,907,053
601,738
35,866
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How can I get the value of an environment variable in Python?
<p>How can I get the value of an environment variable in Python?</p>
[ { "answerId": 4907053, "score": 4869, "isAccepted": true, "createdAt": "2011-02-05T13:18:00", "ownerDisplayName": "Rod", "ownerUserId": 64633, "bodyText": "Environment variables are accessed through os.environ : import os print(os.environ['HOME']) To see a list of all environment variabl...
1
613183
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
613,183
How do I sort a dictionary by value?
3,413
5,839,599
34
true
true
[ "python", "sorting", "dictionary" ]
2009-03-05T00:49:05
2025-07-16T09:04:20
Gern Blanston
false
CC BY-SA 4.0
613,218
2,786
42,680
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question here How do I sort a list of dictionaries by a...
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question here <em><a href="https://s...
[ { "answerId": 613218, "score": 7099, "isAccepted": true, "createdAt": "2009-03-05T00:59:34", "ownerDisplayName": "Devin Jeanpierre", "ownerUserId": 18515, "bodyText": "Python 3.7+ or CPython 3.6 Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementatio...
1
2612802
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
2,612,802
How do I clone a list so that it doesn't change unexpectedly after assignment?
3,371
2,303,961
25
true
true
[ "python", "list", "clone", "mutable" ]
2010-04-10T08:49:46
2025-12-21T05:36:37
aF.
false
CC BY-SA 4.0
2,612,815
187,730
67,093
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
While using new_list = my_list , any modifications to new_list changes my_list every time. Why is this, and how can I clone or copy the list to prevent it? For example: >>> my_list = [1, 2, 3] >>> new_list = my_list >>> new_list.append(4) >>> my_list [1, 2, 3, 4]
<p>While using <code>new_list = my_list</code>, any modifications to <code>new_list</code> changes <code>my_list</code> every time. Why is this, and how can I clone or copy the list to prevent it? For example:</p> <pre><code>&gt;&gt;&gt; my_list = [1, 2, 3] &gt;&gt;&gt; new_list = my_list &gt;&gt;&gt; new_list.append(4...
[ { "answerId": 2612815, "score": 4158, "isAccepted": true, "createdAt": "2010-04-10T08:55:21", "ownerDisplayName": "Felix Kling", "ownerUserId": 218196, "bodyText": "new_list = my_list doesn't actually create a second list. The assignment just copies the reference to the list, not the act...
1
986006
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
986,006
How do I pass a variable by reference?
3,364
2,218,487
44
true
true
[ "python", "reference", "parameter-passing", "pass-by-reference" ]
2009-06-12T10:23:51
2025-10-14T23:11:08
David Sykes
false
CC BY-SA 4.0
986,145
259
50,122
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I wrote this class for testing: class PassByReference: def __init__(self): self.variable = 'Original' self.change(self.variable) print(self.variable) def change(self, var): var = 'Changed' When I tried creating an instance, the output was Original . So it seems like parameters in Python are passed by value. Is that cor...
<p>I wrote this class for testing:</p> <pre><code>class PassByReference: def __init__(self): self.variable = 'Original' self.change(self.variable) print(self.variable) def change(self, var): var = 'Changed' </code></pre> <p>When I tried creating an instance, the output was <code...
[ { "answerId": 986145, "score": 3596, "isAccepted": true, "createdAt": "2009-06-12T11:18:27", "ownerDisplayName": "Blair Conrad", "ownerUserId": 1199, "bodyText": "Arguments are passed by assignment . The rationale behind this is twofold: the parameter passed in is actually a reference to...
1
2052390
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
2,052,390
Manually raising (throwing) an exception in Python
3,322
3,379,634
11
true
true
[ "python", "exception" ]
2010-01-12T21:07:40
2025-07-12T13:46:05
TIMEX
false
CC BY-SA 4.0
24,065,533
179,736
275,536
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I raise an exception in Python so that it can later be caught via an except block?
<p>How do I raise an exception in Python so that it can later be caught via an <code>except</code> block?</p>
[ { "answerId": 24065533, "score": 4329, "isAccepted": true, "createdAt": "2014-06-05T16:30:58", "ownerDisplayName": "Aaron Hall", "ownerUserId": 541136, "bodyText": "How do I manually throw/raise an exception in Python? Use the most specific Exception constructor that semantically fits yo...
1
576169
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
576,169
Understanding Python super() with __init__() methods
3,298
2,981,060
7
true
true
[ "python", "class", "oop", "inheritance", "super" ]
2009-02-23T00:30:08
2024-04-02T17:51:25
Mizipzor
true
null
576,183
56,763
52,749
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Why is super() used? Is there a difference between using Base.__init__ and super().__init__ ? class Base(object): def __init__(self): print "Base created" class ChildA(Base): def __init__(self): Base.__init__(self) class ChildB(Base): def __init__(self): super(ChildB, self).__init__() ChildA() ChildB()
<p>Why is <code>super()</code> used?</p> <p>Is there a difference between using <code>Base.__init__</code> and <code>super().__init__</code>?</p> <pre><code>class Base(object): def __init__(self): print &quot;Base created&quot; class ChildA(Base): def __init__(self): Base.__init__(self)...
[ { "answerId": 576183, "score": 2382, "isAccepted": true, "createdAt": "2009-02-23T00:37:31", "ownerDisplayName": "Kiv", "ownerUserId": 49559, "bodyText": "super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inherita...
1
1720421
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1720421/how-do-i-concatenate-two-lists-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,720,421
How do I concatenate two lists in Python?
3,237
4,907,006
31
true
true
[ "python", "list", "concatenation" ]
2009-11-12T07:04:09
2024-01-10T20:15:51
y2k
false
CC BY-SA 4.0
1,720,432
206,504
66,254
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I concatenate two lists in Python? Example: listone = [1, 2, 3] listtwo = [4, 5, 6] Expected outcome: >>> joinedlist [1, 2, 3, 4, 5, 6]
<p>How do I concatenate two lists in Python?</p> <p>Example:</p> <pre><code>listone = [1, 2, 3] listtwo = [4, 5, 6] </code></pre> <p>Expected outcome:</p> <pre><code>&gt;&gt;&gt; joinedlist [1, 2, 3, 4, 5, 6] </code></pre>
[ { "answerId": 1720432, "score": 5641, "isAccepted": true, "createdAt": "2009-11-12T07:07:06", "ownerDisplayName": "Daniel G", "ownerUserId": 207432, "bodyText": "Use the + operator to combine the lists: listone = [1, 2, 3] listtwo = [4, 5, 6] joinedlist = listone + listtwo Output: >>> jo...
1
53513
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
53,513
How do I check if a list is empty?
3,222
5,405,158
27
true
true
[ "python", "list" ]
2008-09-10T06:20:11
2026-07-06T03:45:10
Ray
false
CC BY-SA 4.0
53,522
4,872
194,066
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
For example, if passed the following: a = [] How do I check to see if a is empty?
<p>For example, if passed the following:</p> <pre><code>a = [] </code></pre> <p>How do I check to see if <code>a</code> is empty?</p>
[ { "answerId": 53522, "score": 7318, "isAccepted": true, "createdAt": "2008-09-10T06:28:05", "ownerDisplayName": "Patrick", "ownerUserId": 429, "bodyText": "if not a: print(\"List is empty\") Using the implicit booleanness of the empty list is quite Pythonic." } ]
1
739654
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/739654/how-do-i-make-function-decorators-and-chain-them-together
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
739,654
How do I make function decorators and chain them together?
3,202
699,294
22
true
true
[ "python", "function", "decorator", "python-decorators", "chain" ]
2009-04-11T07:05:31
2023-10-08T00:52:58
Imran
false
CC BY-SA 4.0
739,665
1,897
91,875
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I make two decorators in Python that would do the following? @make_bold @make_italic def say(): return "Hello" Calling say() should return: "<b><i>Hello</i></b>"
<p>How do I make two decorators in Python that would do the following?</p> <pre><code>@make_bold @make_italic def say(): return &quot;Hello&quot; </code></pre> <p>Calling <code>say()</code> should return:</p> <pre><code>&quot;&lt;b&gt;&lt;i&gt;Hello&lt;/i&gt;&lt;/b&gt;&quot; </code></pre>
[ { "answerId": 1594484, "score": 4896, "isAccepted": false, "createdAt": "2009-10-20T13:05:46", "ownerDisplayName": "Bite code", "ownerUserId": 9951, "bodyText": "If you are not into long explanations, see Paolo Bergantino’s answer . Decorator Basics Python’s functions are objects To unde...
2
312443
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/312443/how-do-i-split-a-list-into-equally-sized-chunks
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
312,443
How do I split a list into equally-sized chunks?
3,181
1,796,140
69
true
true
[ "python", "list", "split", "chunks" ]
2008-11-23T12:15:52
2026-02-08T23:06:55
jespern
false
CC BY-SA 4.0
312,464
112,415
33,576
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I split a list of arbitrary length into equal sized chunks? See also: How to iterate over a list in chunks . To chunk strings, see Split string every nth character? .
<p>How do I split a list of arbitrary length into equal sized chunks?</p> <hr /> <p><sub>See also: <a href="https://stackoverflow.com/q/434287">How to iterate over a list in chunks</a>.<br /> To chunk strings, see <a href="https://stackoverflow.com/questions/9475241">Split string every nth character?</a>.</sub></p>
[ { "answerId": 312464, "score": 4506, "isAccepted": true, "createdAt": "2008-11-23T12:33:53", "ownerDisplayName": "Ned Batchelder", "ownerUserId": 14343, "bodyText": "Here's a generator that yields evenly-sized chunks: def chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\...
1
5137497
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/5137497/find-the-current-directory-and-files-directory
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
5,137,497
Find the current directory and file's directory
3,144
5,513,037
13
true
true
[ "python", "directory" ]
2011-02-28T01:51:21
2023-03-15T08:40:13
John Howard
true
null
5,137,509
374,797
65,043
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I determine: the current directory (where I was in the shell when I ran the Python script), and where the Python file I am executing is?
<p>How do I determine:</p> <ol> <li>the current directory (where I was in the shell when I ran the Python script), and</li> <li>where the Python file I am executing is?</li> </ol>
[ { "answerId": 5137509, "score": 4848, "isAccepted": true, "createdAt": "2011-02-28T01:54:18", "ownerDisplayName": "Russell Dias", "ownerUserId": 322129, "bodyText": "To get the full path to the directory a Python file is contained in, write this in that file: import os dir_path = os.path...
1
252703
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/252703/what-is-the-difference-between-pythons-list-methods-append-and-extend
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
252,703
What is the difference between Python's list methods append and extend?
3,109
3,327,880
20
true
true
[ "python", "list", "data-structures", "append", "extend" ]
2008-10-31T05:55:36
2024-04-24T20:34:06
Claudiu
false
CC BY-SA 4.0
252,711
15,055
231,141
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
What's the difference between the list methods append() and extend() ?
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
[ { "answerId": 252711, "score": 5933, "isAccepted": true, "createdAt": "2008-10-31T06:02:25", "ownerDisplayName": "kender", "ownerUserId": 4172, "bodyText": ".append() appends a single object at the end of the list: >>> x = [1, 2, 3] >>> x.append([4, 5]) >>> print(x) [1, 2, 3, [4, 5]] .ex...
1
11346283
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/11346283/renaming-column-names-in-pandas
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
11,346,283
Renaming column names in Pandas
3,074
7,035,834
33
true
true
[ "python", "pandas", "replace", "dataframe", "rename" ]
2012-07-05T14:21:15
2025-05-23T08:56:42
user1504276
false
CC BY-SA 4.0
11,346,337
1,504,276
30,835
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I want to change the column labels of a Pandas DataFrame from ['$a', '$b', '$c', '$d', '$e'] to ['a', 'b', 'c', 'd', 'e']
<p>I want to change the column labels of a Pandas DataFrame from</p> <pre><code>['$a', '$b', '$c', '$d', '$e'] </code></pre> <p>to</p> <pre><code>['a', 'b', 'c', 'd', 'e'] </code></pre>
[ { "answerId": 11354850, "score": 4718, "isAccepted": false, "createdAt": "2012-07-06T01:48:15", "ownerDisplayName": "lexual", "ownerUserId": 1505540, "bodyText": "Rename Specific Columns Use the df.rename() function and refer the columns to be renamed. Not all the columns have to be rena...
2
30081275
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/30081275/why-is-1000000000000000-in-range1000000000000001-so-fast-in-python-3
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
30,081,275
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
3,069
385,681
12
true
true
[ "python", "performance", "python-3.x", "range", "python-internals" ]
2015-05-06T15:32:43
2023-05-19T08:43:44
Rick
false
CC BY-SA 4.0
30,081,318
2,437,514
45,759
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
It is my understanding that the range() function, which is actually an object type in Python 3 , generates its contents on the fly, similar to a generator. This being the case, I would have expected the following line to take an inordinate amount of time because, in order to determine whether 1 quadrillion is in the ra...
<p>It is my understanding that the <code>range()</code> function, which is actually <a href="https://docs.python.org/3/library/stdtypes.html#typesseq-range" rel="noreferrer">an object type in Python 3</a>, generates its contents on the fly, similar to a generator.</p> <p>This being the case, I would have expected the f...
[ { "answerId": 30081318, "score": 3130, "isAccepted": true, "createdAt": "2015-05-06T15:33:58", "ownerDisplayName": "Martijn Pieters", "ownerUserId": 100297, "bodyText": "The Python 3 range() object doesn't produce numbers immediately; it is a smart sequence object that produces numbers o...
1
11277432
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/11277432/how-can-i-remove-a-key-from-a-python-dictionary
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
11,277,432
How can I remove a key from a Python dictionary?
3,023
3,132,797
11
true
true
[ "python", "dictionary", "unset" ]
2012-06-30T20:27:59
2024-11-02T13:47:58
Tony
false
CC BY-SA 4.0
11,277,439
692,499
38,801
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I want to remove a key from a dictionary if it is present. I currently use this code: if key in my_dict: del my_dict[key] Without the if statement, the code will raise KeyError if the key is not present. How can I handle this more simply? See Delete an element from a dictionary for more general approaches to the proble...
<p>I want to remove a key from a dictionary if it is present. I currently use this code:</p> <pre class="lang-py prettyprint-override"><code>if key in my_dict: del my_dict[key] </code></pre> <p>Without the <code>if</code> statement, the code will raise <code>KeyError</code> if the key is <em>not</em> present. How c...
[ { "answerId": 11277439, "score": 4828, "isAccepted": true, "createdAt": "2012-06-30T20:29:18", "ownerDisplayName": "Sven Marnach", "ownerUserId": 279627, "bodyText": "To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop() : my_dict.pop('key...
1
466345
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/466345/convert-string-jun-1-2005-133pm-into-datetime
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
466,345
Convert string "Jun 1 2005 1:33PM" into datetime
3,005
4,732,556
26
true
true
[ "python", "datetime", "type-conversion" ]
2009-01-21T18:00:29
2024-07-10T01:05:18
Oli
false
CC BY-SA 4.0
466,376
12,870
240,946
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I have a huge list of datetime strings like the following ["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"] How do I convert them into datetime objects?
<p>I have a huge list of datetime strings like the following</p> <pre class="lang-py prettyprint-override"><code>[&quot;Jun 1 2005 1:33PM&quot;, &quot;Aug 28 1999 12:00AM&quot;] </code></pre> <p>How do I convert them into <a href="https://docs.python.org/3/library/datetime.html#datetime-objects" rel="noreferrer"><code>...
[ { "answerId": 466376, "score": 4471, "isAccepted": true, "createdAt": "2009-01-21T18:08:52", "ownerDisplayName": "Patrick Harrington", "ownerUserId": 41165, "bodyText": "datetime.strptime parses an input string in the user-specified format into a timezone-naive datetime object: >>> from ...
1
2720014
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/2720014/how-to-upgrade-all-python-packages-with-pip
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
2,720,014
How to upgrade all Python packages with pip
2,898
2,135,598
67
true
true
[ "python", "pip", "pypi" ]
2010-04-27T09:23:25
2026-05-11T05:59:35
thedjpetersen
false
CC BY-SA 4.0
3,452,888
324,085
29,695
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Is it possible to upgrade all Python packages at one time with pip ? Note : that there is a feature request for this on the official issue tracker.
<p>Is it possible to upgrade all Python packages at one time with <strong><a href="https://pypi.python.org/pypi/pip" rel="noreferrer"><code>pip</code></a></strong>?</p> <p><strong>Note</strong>: that there is <a href="https://github.com/pypa/pip/issues/4551" rel="noreferrer">a feature request</a> for this on the offici...
[ { "answerId": 3452888, "score": 2957, "isAccepted": true, "createdAt": "2010-08-10T19:56:49", "ownerDisplayName": "rbp", "ownerUserId": 158773, "bodyText": "There isn't a built-in flag yet. Starting with pip version 22.3, the --outdated and --format=freeze have become mutually exclusive ...
1
72899
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/72899/how-can-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
72,899
How can I sort a list of dictionaries by a value of the dictionary in Python?
2,859
1,492,821
22
true
true
[ "python", "list", "sorting", "dictionary", "data-structures" ]
2008-09-16T14:27:47
2025-07-23T17:11:37
masi
false
CC BY-SA 4.0
73,050
12,398
118
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I sort a list of dictionaries by a specific key's value? Given: [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}] When sorted by name , it should become: [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
<p>How do I sort a list of dictionaries by a specific key's value? Given:</p> <pre class="lang-py prettyprint-override"><code>[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}] </code></pre> <p>When sorted by <code>name</code>, it should become:</p> <pre class="lang-py prettyprint-override"><code>[{'name': 'Ba...
[ { "answerId": 73050, "score": 3749, "isAccepted": true, "createdAt": "2008-09-16T14:39:44", "ownerDisplayName": "Mario F", "ownerUserId": 3785, "bodyText": "The sorted() function takes a key= parameter newlist = sorted(list_to_be_sorted, key=lambda d: d['name']) Alternatively, you can us...
1
990754
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/990754/how-to-leave-exit-deactivate-a-python-virtualenv
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
990,754
How to leave/exit/deactivate a Python virtualenv
2,856
3,231,537
16
true
true
[ "python", "virtualenv", "exit", "virtualenvwrapper" ]
2009-06-13T14:15:36
2025-08-12T20:00:36
Apreche
false
CC BY-SA 4.0
990,779
65,326
33,919
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ How do I exit all virtual environments and work on my system environment again? Righ...
<p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the <code>workon</code> command.</p> <pre><code>me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ </code></pre> <p>How do I exit all virtual environme...
[ { "answerId": 990779, "score": 4559, "isAccepted": true, "createdAt": "2009-06-13T14:31:00", "ownerDisplayName": "Brandon Rhodes", "ownerUserId": 85360, "bodyText": "Usually, activating a virtualenv gives you a shell function named: $ deactivate which puts things back to normal. I have j...
1
930397
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/930397/how-do-i-get-the-last-element-of-a-list
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
930,397
How do I get the last element of a list?
2,814
3,388,910
19
true
true
[ "python", "list" ]
2009-05-30T19:28:53
2026-05-23T08:12:06
Janusz
false
CC BY-SA 4.0
930,398
114,066
190,122
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I get the last element of a list in Python? I tried: alist[::-1] but I got ValueError: attempt to assign sequence of size 6 to extended slice of size 5
<p>How do I get the last element of a list in Python? I tried:</p> <pre class="lang-py prettyprint-override"><code>alist[::-1] </code></pre> <p>but I got</p> <blockquote> <p>ValueError: attempt to assign sequence of size 6 to extended slice of size 5</p> </blockquote>
[ { "answerId": 930398, "score": 4020, "isAccepted": true, "createdAt": "2009-05-30T19:29:55", "ownerDisplayName": "Sasha Chedygov", "ownerUserId": 104184, "bodyText": "some_list[-1] is the shortest and most Pythonic. In fact, you can do much more with this syntax. The some_list[-n] syntax...
1
379906
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
379,906
How do I parse a string to a float or int?
2,786
4,896,165
34
true
true
[ "python", "parsing", "floating-point", "type-conversion", "integer" ]
2008-12-19T01:52:26
2026-05-29T15:50:33
Tristan Havelick
false
CC BY-SA 4.0
379,910
30,529
70,466
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How can I convert an str to a float ? "545.2222" -> 545.2222 Or an str to a int ? "31" -> 31 For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it . Please instead use How can I read inputs as numbers? to close duplicate questions where OP received a string from...
<p>How can I convert an <code>str</code> to a <code>float</code>?</p> <pre><code>&quot;545.2222&quot; -&gt; 545.2222 </code></pre> <p>Or an <code>str</code> to a <code>int</code>?</p> <pre><code>&quot;31&quot; -&gt; 31 </code></pre> <hr /> <p><sub>For the reverse, see <a href="https://stackoverflow.com/questions/961632...
[ { "answerId": 379910, "score": 3126, "isAccepted": true, "createdAt": "2008-12-19T01:54:51", "ownerDisplayName": "Harley Holcombe", "ownerUserId": 1057, "bodyText": ">>> a = \"545.2222\" >>> float(a) 545.22220000000004 >>> int(float(a)) 545" } ]
1
4750806
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/4750806/how-do-i-install-pip-on-windows
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
4,750,806
How do I install pip on Windows?
2,778
3,605,983
41
true
true
[ "python", "windows", "pip" ]
2011-01-20T18:08:59
2026-01-27T02:42:43
mit
false
CC BY-SA 4.0
12,476,379
362,951
11,360
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
pip is a replacement for easy_install . But should I install pip using easy_install on Windows? Is there a better way?
<p><a href="https://pip.pypa.io/en/stable/" rel="noreferrer"><code>pip</code></a> is a replacement for <a href="http://setuptools.readthedocs.io/en/latest/easy_install.html" rel="noreferrer"><code>easy_install</code></a>. But should I install <code>pip</code> using <code>easy_install</code> on Windows? Is there a bette...
[ { "answerId": 12476379, "score": 1967, "isAccepted": true, "createdAt": "2012-09-18T11:45:33", "ownerDisplayName": "Colonel Panic", "ownerUserId": 284795, "bodyText": "Python 3.4+ and 2.7.9+ Good news! Python 3.4 (released March 2014) and Python 2.7.9 (released December 2014) ship with P...
1
663171
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/663171/how-do-i-get-a-substring-of-a-string-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
663,171
How do I get a substring of a string in Python?
2,728
4,175,571
16
true
true
[ "python", "string", "substring" ]
2009-03-19T17:29:41
2024-09-26T09:43:43
Joan Venge
true
null
663,175
51,816
334,709
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I want to get a new string from the third character to the end of the string, e.g. myString[2:end] . If omitting the second part means 'to the end', and if you omit the first part, does it start from the start?
<p>I want to get a new string from the third character to the end of the string, e.g. <code>myString[2:end]</code>. If omitting the second part means 'to the end', and if you omit the first part, does it start from the start?</p>
[ { "answerId": 663175, "score": 3835, "isAccepted": true, "createdAt": "2009-03-19T17:30:44", "ownerDisplayName": "Paolo Bergantino", "ownerUserId": 16417, "bodyText": ">>> x = \"Hello World!\" >>> x[2:] 'llo World!' >>> x[:2] 'He' >>> x[:-2] 'Hello Worl' >>> x[-2:] 'd!' >>> x[2:-2] 'llo ...
1
5466451
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/5466451/how-do-i-escape-curly-brace-characters-characters-in-a-string-while-using
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
5,466,451
How do I escape curly-brace ({}) characters characters in a string while using .format?
2,723
1,313,295
24
true
true
[ "python", "string", "format", "string-formatting", "curly-braces" ]
2011-03-29T00:04:53
2026-04-02T16:13:24
Schitti
false
CC BY-SA 4.0
5,466,478
242,670
28,459
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Non-working example: print(" \{ Hello \} {0} ".format(42)) Desired output: {Hello} 42
<p>Non-working example:</p> <pre><code>print(&quot; \{ Hello \} {0} &quot;.format(42)) </code></pre> <p>Desired output:</p> <pre class="lang-none prettyprint-override"><code> {Hello} 42 </code></pre>
[ { "answerId": 5466478, "score": 3573, "isAccepted": true, "createdAt": "2011-03-29T00:08:55", "ownerDisplayName": "Greg Hewgill", "ownerUserId": 893, "bodyText": "You need to double the {{ and }} : >>> x = \" {{ Hello }} {0} \" >>> print(x.format(42)) ' { Hello } 42 ' Here's the relevant...
1
1602934
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,602,934
Check if a given key already exists in a dictionary
2,675
7,335,561
16
true
true
[ "python", "dictionary" ]
2009-10-21T19:05:09
2023-03-07T14:12:21
Mohan Gulati
false
CC BY-SA 3.0
1,602,964
112,850
28,219
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: if 'key1' in dict.keys(): print "blah" else: print "boo" I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the d...
[ { "answerId": 1602964, "score": 5730, "isAccepted": true, "createdAt": "2009-10-21T19:10:21", "ownerDisplayName": "Chris B.", "ownerUserId": 9161, "bodyText": "in tests for the existence of a key in a dict : d = {\"key1\": 10, \"key2\": 23} if \"key1\" in d: print(\"this will execute\") ...
1
68645
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/68645/class-static-variables-and-methods
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
68,645
Class (static) variables and methods
2,636
1,841,328
27
true
true
[ "python", "class", "static", "class-variables" ]
2008-09-16T01:46:36
2024-01-30T14:39:08
Andrew Walker
false
CC BY-SA 4.0
68,672
2,246
42,810
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I create class (i.e. static ) variables or methods in Python?
<p>How do I create class (i.e. <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods" rel="noreferrer">static</a>) variables or methods in Python?</p>
[ { "answerId": 68672, "score": 2408, "isAccepted": true, "createdAt": "2008-09-16T01:51:06", "ownerDisplayName": "Blair Conrad", "ownerUserId": 1199, "bodyText": "Variables declared inside the class definition, but not inside a method are class or static variables: >>> class MyClass: ... ...
1
6797984
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/6797984/how-do-i-lowercase-a-string-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
6,797,984
How do I lowercase a string in Python?
2,587
3,221,402
10
true
true
[ "python", "string", "uppercase", "lowercase" ]
2011-07-23T03:08:53
2025-03-19T22:13:07
Benjamin Didur
false
CC BY-SA 4.0
6,797,990
858,922
26,071
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Is there a way to convert a string to lowercase? "Kilometers" → "kilometers" See How to change a string into uppercase? for the opposite.
<p>Is there a way to convert a string to lowercase?</p> <pre><code>&quot;Kilometers&quot; → &quot;kilometers&quot; </code></pre> <hr /> <p><sub>See <a href="https://stackoverflow.com/questions/9257094">How to change a string into uppercase?</a> for the opposite.</sub></p>
[ { "answerId": 6797990, "score": 3667, "isAccepted": true, "createdAt": "2011-07-23T03:09:58", "ownerDisplayName": "Petar Ivanov", "ownerUserId": 791998, "bodyText": "Use str.lower() : \"Kilometer\".lower()" } ]
1
610883
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/610883/how-can-i-check-if-an-object-has-an-attribute
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
610,883
How can I check if an object has an attribute?
2,536
1,630,932
16
true
true
[ "python", "class", "object", "attributes", "attributeerror" ]
2009-03-04T14:45:59
2025-11-22T02:35:49
Lucas Gabriel Sánchez
false
CC BY-SA 4.0
610,893
20,601
42,035
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I check if an object has some attribute? For example: >>> a = SomeClass() >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' How do I tell if a has the attribute property before using it?
<p>How do I check if an object has some attribute? For example:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; a = SomeClass() &gt;&gt;&gt; a.property Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; AttributeError: SomeClass instance has no attribute 'p...
[ { "answerId": 610893, "score": 3523, "isAccepted": true, "createdAt": "2009-03-04T14:48:43", "ownerDisplayName": "Jarret Hardie", "ownerUserId": 72247, "bodyText": "Try hasattr() : if hasattr(a, 'property'): a.property See zweiterlinde's answer , which offers good advice about asking for...
1
493386
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/493386/how-to-print-without-a-newline-or-space
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
493,386
How to print without a newline or space
2,534
2,686,093
30
true
true
[ "python", "trailing-newline" ]
2009-01-29T20:58:25
2024-05-31T10:28:49
Andrea Ambu
false
CC BY-SA 4.0
493,399
21,384
39,976
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Consider these examples using print in Python: >>> for i in range(4): print('.') . . . . >>> print('.', '.', '.', '.') . . . . Either a newline or a space is added between each value. How can I avoid that, so that the output is .... instead? In other words, how can I "append" strings to the standard output stream?
<p>Consider these examples using <code>print</code> in Python:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; for i in range(4): print('.') . . . . &gt;&gt;&gt; print('.', '.', '.', '.') . . . . </code></pre> <p>Either a newline or a space is added between each value. How can I avoid that, so that the...
[ { "answerId": 493399, "score": 3434, "isAccepted": true, "createdAt": "2009-01-29T21:01:43", "ownerDisplayName": "codelogic", "ownerUserId": 43427, "bodyText": "In Python 3, you can use the sep= and end= parameters of the print function: To not add a newline to the end of the string: pri...
1
3061
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
3,061
Calling a function of a module by using its name (a string)
2,496
1,261,897
19
true
true
[ "python", "object", "reflection" ]
2008-08-06T03:36:08
2024-08-23T17:41:09
ricree
false
CC BY-SA 4.0
3,071
121
36,972
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I call a function, using a string with the function's name? For example: import foo func_name = "bar" call(foo, func_name) # calls foo.bar()
<p>How do I call a function, using a string with the function's name? For example:</p> <pre><code>import foo func_name = &quot;bar&quot; call(foo, func_name) # calls foo.bar() </code></pre>
[ { "answerId": 3071, "score": 2985, "isAccepted": true, "createdAt": "2008-08-06T03:57:16", "ownerDisplayName": "Patrick Johnmeyer", "ownerUserId": 363, "bodyText": "Given a module foo with method bar : import foo bar = getattr(foo, 'bar') result = bar() getattr can similarly be used on c...
1
306400
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/306400/how-can-i-randomly-select-choose-an-item-from-a-list-get-a-random-element
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
306,400
How can I randomly select (choose) an item from a list (get a random element)?
2,444
2,490,228
18
true
true
[ "python", "list", "random" ]
2008-11-20T18:42:21
2023-08-31T22:53:30
Ray
false
CC BY-SA 4.0
306,417
4,872
194,066
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I retrieve an item at random from the following list? foo = ['a', 'b', 'c', 'd', 'e']
<p>How do I retrieve an item at random from the following list?</p> <pre class="lang-py prettyprint-override"><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre>
[ { "answerId": 306417, "score": 3546, "isAccepted": true, "createdAt": "2008-11-20T18:46:39", "ownerDisplayName": "Pēteris Caune", "ownerUserId": 5821, "bodyText": "Use random.choice() : import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) For cryptographically secure r...
1
627435
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
627,435
How to remove an element from a list by index
2,348
4,355,248
18
true
true
[ "python", "list", "indexing" ]
2009-03-09T18:16:11
2022-08-30T20:15:38
Joan Venge
false
CC BY-SA 4.0
627,453
51,816
334,709
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I remove an element from a list by index ? I found list.remove() , but this slowly scans the list for an item by value .
<p>How do I remove an element from a list <strong>by index</strong>?</p> <p>I found <code>list.remove()</code>, but this slowly scans the list for an item <strong>by value</strong>.</p>
[ { "answerId": 627453, "score": 2613, "isAccepted": true, "createdAt": "2009-03-09T18:21:24", "ownerDisplayName": "unbeknown", "ownerUserId": null, "bodyText": "Use del and specify the index of the element you want to delete: >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> del a[-1] >>> a [0, ...
1
13411544
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/13411544/delete-a-column-from-a-pandas-dataframe
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
13,411,544
Delete a column from a Pandas DataFrame
2,341
4,669,824
23
true
true
[ "python", "pandas", "dataframe", "del" ]
2012-11-16T06:26:40
2025-10-22T10:10:47
John
false
CC BY-SA 4.0
13,485,766
390,388
43,780
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
To delete a column in a DataFrame, I can successfully use: del df['column_name'] But why can't I use the following? del df.column_name Since it is possible to access the Series via df.column_name , I expected this to work.
<p>To delete a column in a DataFrame, I can successfully use:</p> <pre class="lang-py prettyprint-override"><code>del df['column_name'] </code></pre> <p>But why can't I use the following?</p> <pre class="lang-py prettyprint-override"><code>del df.column_name </code></pre> <p>Since it is possible to access the Series vi...
[ { "answerId": 18145399, "score": 3756, "isAccepted": false, "createdAt": "2013-08-09T11:12:09", "ownerDisplayName": "LondonRob", "ownerUserId": 2071807, "bodyText": "The best way to do this in Pandas is to use drop : df = df.drop('column_name', axis=1) where 1 is the axis number ( 0 for ...
1
1712227
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1712227/how-do-i-get-the-number-of-elements-in-a-list-length-of-a-list-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,712,227
How do I get the number of elements in a list (length of a list) in Python?
2,307
4,059,753
11
true
true
[ "python", "list" ]
2009-11-11T00:30:54
2024-07-02T12:05:02
y2k
false
CC BY-SA 4.0
1,712,236
206,504
66,254
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I get the number of elements in the list items ? items = ["apple", "orange", "banana"] # There are 3 items.
<p>How do I get the number of elements in the list <code>items</code>?</p> <pre><code>items = [&quot;apple&quot;, &quot;orange&quot;, &quot;banana&quot;] # There are 3 items. </code></pre>
[ { "answerId": 1712236, "score": 2992, "isAccepted": true, "createdAt": "2009-11-11T00:33:22", "ownerDisplayName": "gnud", "ownerUserId": 27204, "bodyText": "The len() function can be used with several different types in Python - both built-in types and library types. For example: >>> len...
1
41573587
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/41573587/what-is-the-difference-between-venv-pyvenv-pyenv-virtualenv-virtualenvwrappe
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
41,573,587
What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?
2,271
777,444
9
true
true
[ "python", "virtualenv", "virtualenvwrapper", "pyenv", "python-venv" ]
2017-01-10T16:27:43
2026-07-03T17:24:14
Flimm
false
CC BY-SA 4.0
41,573,588
247,696
155,467
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Python 3.3 includes the new package venv in its standard library. What does it do, and how does it differ from all the other packages that match the regex (py)?(v|virtual|pip)?env ?
<p>Python 3.3 includes the new package <code>venv</code> in its standard library. What does it do, and how does it differ from all the other packages that match the regex <code>(py)?(v|virtual|pip)?env</code>?</p>
[ { "answerId": 41573588, "score": 2468, "isAccepted": true, "createdAt": "2017-01-10T16:27:43", "ownerDisplayName": "Flimm", "ownerUserId": 247696, "bodyText": "This is my personal recommendation for beginners: start by learning virtualenv and pip , tools which work with both Python 2 and...
1
339007
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/339007/how-do-i-pad-a-string-with-zeros
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
339,007
How do I pad a string with zeros?
2,262
1,739,821
19
true
true
[ "python", "string", "zero-padding" ]
2008-12-03T22:39:51
2026-03-04T22:54:12
Faisal
false
CC BY-SA 4.0
339,013
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I pad a numeric string with zeroes to the left, so that the string has a specific length?
<p>How do I pad a numeric string with zeroes to the left, so that the string has a specific length?</p>
[ { "answerId": 339013, "score": 3517, "isAccepted": true, "createdAt": "2008-12-03T22:42:04", "ownerDisplayName": "Harley Holcombe", "ownerUserId": 1057, "bodyText": "To pad strings: >>> print('4'.zfill(3)) 004 >>> print('-4'.zfill(3)) -04 To pad numbers: >>> n = 4 >>> print(f'{n:03}') # ...
1
5844672
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
5,844,672
Delete an element from a dictionary
2,249
2,958,095
20
true
true
[ "python", "dictionary", "del" ]
2011-04-30T21:20:57
2025-03-24T16:45:10
richzilla
false
CC BY-SA 4.0
5,844,692
301,032
42,368
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I delete an item from a dictionary in Python? Without modifying the original dictionary, how do I obtain another dictionary with the item removed? See also How can I remove a key from a Python dictionary? for the specific issue of removing an item (by key) that may not already be present.
<ol> <li>How do I delete an item from a dictionary in Python?</li> <li><strong>Without</strong> modifying the original dictionary, how do I obtain <strong>another</strong> dictionary with the item removed?</li> </ol> <hr /> <p><sub>See also <a href="https://stackoverflow.com/questions/11277432">How can I remove a key f...
[ { "answerId": 5844692, "score": 2578, "isAccepted": true, "createdAt": "2011-04-30T21:25:39", "ownerDisplayName": "Greg Hewgill", "ownerUserId": 893, "bodyText": "The del statement removes an element: del d[key] Note that this mutates the existing dictionary, so the contents of the dicti...
1
2225038
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/2225038/determine-the-type-of-an-object
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
2,225,038
Determine the type of an object?
2,231
2,519,455
15
true
true
[ "python", "dictionary", "types", "typeof" ]
2010-02-08T21:37:20
2022-08-29T20:14:36
Justin Ethier
true
null
2,225,066
101,258
134,961
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Is there a simple way to determine if a variable is a list, dictionary, or something else?
<p>Is there a simple way to determine if a variable is a list, dictionary, or something else?</p>
[ { "answerId": 2225066, "score": 2401, "isAccepted": true, "createdAt": "2010-02-08T21:40:06", "ownerDisplayName": "poke", "ownerUserId": 216074, "bodyText": "There are two built-in functions that help you identify the type of an object. You can use type() if you need the exact type of an...
1
9573244
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/9573244/how-to-check-if-the-string-is-empty-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
9,573,244
How to check if the string is empty in Python?
2,229
3,561,301
20
true
true
[ "python", "string", "boolean", "is-empty", "comparison-operators" ]
2012-03-05T20:09:23
2026-05-02T19:28:18
Joan Venge
false
CC BY-SA 4.0
9,573,259
51,816
334,709
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Does Python have something like an empty string variable where you can do: if myString == string.empty: Regardless, what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good.
<p>Does Python have something like an empty string variable where you can do:</p> <pre class="lang-python prettyprint-override"><code>if myString == string.empty: </code></pre> <p>Regardless, what's the most elegant way to check for empty string values? I find hard coding <code>&quot;&quot;</code> every time for checki...
[ { "answerId": 9573259, "score": 3169, "isAccepted": true, "createdAt": "2012-03-05T20:10:21", "ownerDisplayName": "Andrew Clark", "ownerUserId": 505154, "bodyText": "Empty strings are \"falsy\" ( python 2 or python 3 reference), which means they are considered false in a Boolean context,...
1
2600191
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/2600191/how-do-i-count-the-occurrences-of-a-list-item
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
2,600,191
How do I count the occurrences of a list item?
2,229
3,167,734
30
true
true
[ "python", "list", "count" ]
2010-04-08T13:30:00
2026-01-01T18:03:01
weakish
false
CC BY-SA 4.0
2,600,208
222,893
30,310
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Given a single item, how do I count occurrences of it in a list, in Python? A related but different problem is counting occurrences of each different element in a collection, getting a dictionary or list as a histogram result instead of a single integer. For that problem, see Using a dictionary to count the items in a ...
<p>Given a single item, how do I count occurrences of it in a list, in Python?</p> <hr /> <p><sub>A related but different problem is counting occurrences of <strong>each different element</strong> in a collection, getting a dictionary or list as a histogram result instead of a single integer. For that problem, see <a h...
[ { "answerId": 2600208, "score": 2566, "isAccepted": true, "createdAt": "2010-04-08T13:31:52", "ownerDisplayName": "Łukasz", "ownerUserId": 4999, "bodyText": "If you only want a single item's count, use the count method: >>> [1, 2, 3, 4, 1, 4, 1].count(1) 3 Important: this is very slow if...
2
9371238
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/9371238/why-is-reading-lines-from-stdin-much-slower-in-c-than-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
9,371,238
Why is reading lines from stdin much slower in C++ than Python?
2,203
325,429
11
true
true
[ "python", "c++", "benchmarking", "iostream", "getline" ]
2012-02-21T02:17:50
2024-09-23T13:19:46
JJC
false
CC BY-SA 4.0
9,371,717
379,037
10,143
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is rusty and I'm not yet an expert Pythonista, please tell me if I'm doing something wrong or if I'm misunderstanding someth...
<p>I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is rusty and I'm not yet an expert Pythonista, please tell me if I'm doing something wrong or if I'm misunderstanding som...
[ { "answerId": 9371717, "score": 1963, "isAccepted": true, "createdAt": "2012-02-21T03:24:19", "ownerDisplayName": "Vaughn Cato", "ownerUserId": 951890, "bodyText": "tl;dr: Because of different default settings in C++ requiring more system calls. By default, cin is synchronized with stdio...
1
493819
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/493819/why-is-it-string-joinlist-instead-of-list-joinstring
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
493,819
Why is it string.join(list) instead of list.join(string)?
2,168
1,577,880
10
true
true
[ "python", "string", "list" ]
2009-01-29T22:45:13
2026-07-10T05:16:54
Evan Fosmark
false
CC BY-SA 4.0
493,842
49,701
102,727
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
This has always confused me. It seems like this would be nicer: ["Hello", "world"].join("-") Than this: "-".join(["Hello", "world"]) Is there a specific reason it is like this?
<p>This has always confused me. It seems like this would be nicer:</p> <pre><code>[&quot;Hello&quot;, &quot;world&quot;].join(&quot;-&quot;) </code></pre> <p>Than this:</p> <pre><code>&quot;-&quot;.join([&quot;Hello&quot;, &quot;world&quot;]) </code></pre> <p>Is there a specific reason it is like this?</p>
null
0
4706499
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/4706499/how-do-i-append-to-a-file
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
4,706,499
How do I append to a file?
2,139
2,380,703
12
true
true
[ "python", "file", "append" ]
2011-01-16T16:20:33
2022-10-19T00:55:58
user502039
false
CC BY-SA 4.0
4,706,520
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I append to a file instead of overwriting it?
<p>How do I append to a file instead of overwriting it?</p>
[ { "answerId": 4706520, "score": 3181, "isAccepted": true, "createdAt": "2011-01-16T16:24:05", "ownerDisplayName": "Petter", "ownerUserId": 116186, "bodyText": "Set the mode in open() to \"a\" (append) instead of \"w\" (write): with open(\"test.txt\", \"a\") as myfile: myfile.write(\"appe...
1
101754
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/101754/is-there-a-way-to-run-python-on-android
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
101,754
Is there a way to run Python on Android?
2,083
782,279
23
true
true
[ "android", "python", "jython", "ase", "android-scripting" ]
2008-09-19T13:21:12
2025-12-08T13:21:21
Bite code
false
CC BY-SA 4.0
8,189,603
9,951
601,871
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
We are working on an S60 version and this platform has a nice Python API.. However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together??
<p>We are working on an <a href="http://en.wikipedia.org/wiki/S60_%28software_platform%29" rel="noreferrer">S60</a> version and this platform has a nice Python API..</p> <p>However, there is nothing official about Python on Android, but since <a href="http://en.wikipedia.org/wiki/Jython" rel="noreferrer">Jython</a> ex...
null
0
735975
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/735975/static-methods-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
735,975
Static methods in Python?
2,075
1,333,424
12
true
true
[ "python", "static-methods" ]
2009-04-09T21:23:19
2023-01-22T01:42:44
Joan Venge
false
CC BY-SA 4.0
735,978
51,816
334,709
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Can I define a static method which I can call directly on the class instance? e.g., MyClass.the_static_method()
<p>Can I define a <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods" rel="noreferrer">static method</a> which I can call directly on the class instance? e.g.,</p> <pre><code>MyClass.the_static_method() </code></pre>
[ { "answerId": 735978, "score": 2350, "isAccepted": true, "createdAt": "2009-04-09T21:24:36", "ownerDisplayName": "dbr", "ownerUserId": 745, "bodyText": "Yep, using the staticmethod decorator: class MyClass(object): @staticmethod def the_static_method(x): print(x) MyClass.the_static_metho...
1
5226311
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/5226311/installing-specific-package-version-with-pip
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
5,226,311
Installing specific package version with pip
2,072
3,276,835
12
true
true
[ "python", "mysql", "pip", "pypi", "mysql-python" ]
2011-03-07T22:58:13
2022-12-28T17:21:24
Joe
false
CC BY-SA 4.0
5,226,504
306,374
27,157
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I am trying to install version 1.2.2 of MySQL_python , using a fresh virtualenv created with the --no-site-packages option. The current version shown in PyPi is 1.2.3 . Is there a way to install the older version? I have tried: pip install MySQL_python==1.2.2 However, when installed, it still shows MySQL_python-1.2.3-p...
<p>I am trying to install version 1.2.2 of <code>MySQL_python</code>, using a fresh virtualenv created with the <code>--no-site-packages</code> option. The current version shown in PyPi is <a href="http://pypi.python.org/pypi/MySQL-python/1.2.3" rel="noreferrer">1.2.3</a>. Is there a way to install the older version? I...
null
0
10660435
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/10660435/how-do-i-split-the-definition-of-a-long-string-over-multiple-lines
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
10,660,435
How do I split the definition of a long string over multiple lines?
2,071
2,138,353
31
true
true
[ "python", "string", "multiline", "multilinestring" ]
2012-05-18T22:21:09
2025-01-06T20:15:41
Pablo Mescher
false
CC BY-SA 4.0
10,660,443
1,231,428
27,767
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). E...
<p>I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a <code>+</code> operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code...
[ { "answerId": 10660443, "score": 3267, "isAccepted": true, "createdAt": "2012-05-18T22:22:54", "ownerDisplayName": "Levon", "ownerUserId": 1209279, "bodyText": "Are you talking about multi-line strings? Easy, use triple quotes to start and end them. s = \"\"\" this is a very long string ...
1
12943819
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/12943819/how-to-prettyprint-a-json-file
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
12,943,819
How to prettyprint a JSON file?
2,061
2,580,019
15
true
true
[ "python", "json", "formatting", "pretty-print" ]
2012-10-17T21:38:43
2023-10-22T10:53:24
Colleen
false
CC BY-SA 4.0
12,944,035
892,387
25,957
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I pretty-print a JSON file in Python?
<p>How do I pretty-print a JSON file in Python?</p>
[ { "answerId": 12944035, "score": 3106, "isAccepted": true, "createdAt": "2012-10-17T21:54:12", "ownerDisplayName": "Blender", "ownerUserId": 464744, "bodyText": "Use the indent= parameter of json.dump() or json.dumps() to specify how many spaces to indent by: >>> import json >>> your_jso...
1
15943769
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/15943769/how-do-i-get-the-row-count-of-a-pandas-dataframe
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
15,943,769
How do I get the row count of a Pandas DataFrame?
2,041
4,766,209
20
true
true
[ "python", "pandas", "dataframe" ]
2013-04-11T08:14:08
2024-07-16T00:09:16
yemu
false
CC BY-SA 4.0
15,943,975
2,006,977
28,889
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I get the number of rows of a pandas dataframe df ?
<p>How do I get the number of rows of a pandas dataframe <code>df</code>?</p>
[ { "answerId": 15943975, "score": 3015, "isAccepted": true, "createdAt": "2013-04-11T08:24:29", "ownerDisplayName": "root", "ownerUserId": 1199589, "bodyText": "For a dataframe df , one can use any of the following: len(df.index) df.shape[0] df[df.columns[0]].count() (== number of non-NaN...
1
510972
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/510972/getting-the-class-name-of-an-instance
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
510,972
Getting the class name of an instance
2,036
1,699,238
12
true
true
[ "python", "introspection", "instanceof", "python-datamodel" ]
2009-02-04T11:37:48
2024-08-20T03:18:59
Dan
false
CC BY-SA 4.0
511,059
18,909
35,883
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I find out the name of the class used to create an instance of an object in Python? I'm not sure if I should use the inspect module or parse the __class__ attribute.
<p>How do I find out the name of the class used to create an instance of an object in Python?</p> <p>I'm not sure if I should use the <a href="https://docs.python.org/2/library/inspect.html" rel="noreferrer" title="inspect — Inspect live objects"><code>inspect</code></a> module or parse the <code>__class__</code> attri...
[ { "answerId": 511059, "score": 2641, "isAccepted": true, "createdAt": "2009-02-04T12:02:12", "ownerDisplayName": "sykloid", "ownerUserId": 53850, "bodyText": "Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is wha...
1
354038
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-represents-a-number-float-or-int
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
354,038
How do I check if a string represents a number (float or int)?
2,031
1,834,888
41
true
true
[ "python", "casting", "floating-point", "type-conversion", "integer" ]
2008-12-09T20:03:42
2025-12-01T14:37:56
Daniel Goldberg
false
CC BY-SA 4.0
354,130
40,115
20,776
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I check if a string represents a numeric value in Python? def is_number(s): try: float(s) return True except ValueError: return False The above works, but it seems clunky. Editor's note: If what you are testing comes from user input, it is still a string even if it represents an int or a float . For converting t...
<p>How do I check if a string represents a numeric value in Python?</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>The above works, but it seems clunky.</p> <hr /> <p><sub><strong>Editor's note:</strong> If what you are testing...
null
0
152580
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
152,580
What's the canonical way to check for type in Python?
2,021
1,756,275
21
true
true
[ "python", "types" ]
2008-09-30T11:00:10
2026-04-22T00:18:01
Herge
false
CC BY-SA 4.0
152,596
14,102
22,837
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I check if an object is of a given type, or if it inherits from a given type? How do I check if the object o is of type str ? Editor's note : Beginners often wrongly expect a string to already be "a number" – either expecting Python 3.x input to convert type, or expecting that a string like '1' is also simultane...
<p>How do I check if an object is of a given type, or if it inherits from a given type?</p> <p>How do I check if the object <code>o</code> is of type <code>str</code>?</p> <hr /> <p><sub><strong>Editor's note</strong>: Beginners often wrongly expect a string to already be &quot;a number&quot; – either expecting Python ...
[ { "answerId": 152596, "score": 2364, "isAccepted": true, "createdAt": "2008-09-30T11:07:45", "ownerDisplayName": "Fredrik Johansson", "ownerUserId": 1163767, "bodyText": "Use isinstance to check if o is an instance of str or any subclass of str : if isinstance(o, str): To check if the ty...
1
12179271
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-a-beginner
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
12,179,271
Meaning of @classmethod and @staticmethod for a beginner
2,015
935,782
12
true
true
[ "python", "oop", "static-methods", "class-method" ]
2012-08-29T13:37:33
2026-02-01T01:44:48
user1632861
true
null
12,179,752
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
What do @classmethod and @staticmethod mean in Python, and how are they different? When should I use them, why should I use them, and how should I use them? As far as I understand, @classmethod tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that...
<p>What do <code>@classmethod</code> and <code>@staticmethod</code> mean in Python, and how are they different? <em>When</em> should I use them, <em>why</em> should I use them, and <em>how</em> should I use them?</p> <p>As far as I understand, <code>@classmethod</code> tells a class that it's a method which should be i...
[ { "answerId": 12179752, "score": 3065, "isAccepted": true, "createdAt": "2012-08-29T14:03:03", "ownerDisplayName": "Rostyslav Dzinko", "ownerUserId": 789649, "bodyText": "Though classmethod and staticmethod are quite similar, there's a slight difference in usage for both entities: classm...
1
7225900
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/7225900/how-can-i-install-packages-using-pip-according-to-the-requirements-txt-file-from
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
7,225,900
How can I install packages using pip according to the requirements.txt file from a local directory?
1,999
3,891,230
18
true
true
[ "python", "pip", "virtualenv", "requirements.txt" ]
2011-08-29T03:53:04
2026-01-06T02:15:41
kakarukeys
false
CC BY-SA 4.0
10,429,168
496,852
24,341
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Here is the problem: I have a requirements.txt file that looks like: BeautifulSoup==3.2.0 Django==1.3 Fabric==1.2.0 Jinja2==2.5.5 PyYAML==3.09 Pygments==1.4 SQLAlchemy==0.7.1 South==0.7.3 amqplib==0.6.1 anyjson==0.3 ... I have a local archive directory containing all the packages + others. I have created a new virtuale...
<p>Here is the problem:</p> <p>I have a <code>requirements.txt</code> file that looks like:</p> <pre class="lang-none prettyprint-override"><code>BeautifulSoup==3.2.0 Django==1.3 Fabric==1.2.0 Jinja2==2.5.5 PyYAML==3.09 Pygments==1.4 SQLAlchemy==0.7.1 South==0.7.3 amqplib==0.6.1 anyjson==0.3 ... </code></pre> <p>I have...
[ { "answerId": 15593865, "score": 2651, "isAccepted": false, "createdAt": "2013-03-24T00:47:43", "ownerDisplayName": "Mike Lyons", "ownerUserId": 710332, "bodyText": "This works for everyone: pip install -r /path/to/requirements.txt Explanation: -r, --requirement < filename > Install from...
1
1319615
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1319615/how-do-i-declare-custom-exceptions-in-modern-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,319,615
How do I declare custom exceptions in modern Python?
1,973
1,392,353
17
true
true
[ "python", "python-3.x", "exception", "python-dataclasses", "pep352" ]
2009-08-23T21:29:29
2025-06-24T15:46:38
Nelson
false
CC BY-SA 4.0
1,319,675
144,170
30,272
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception. By "modern Python" I mean something that will run in Python 2....
<p>How do I declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.</p> <p>By &quot;modern Python&quot; I mean something that w...
[ { "answerId": 1319675, "score": 2072, "isAccepted": true, "createdAt": "2009-08-23T21:55:23", "ownerDisplayName": "gahooa", "ownerUserId": 64004, "bodyText": "Maybe I missed the question, but why not: class MyException(Exception): pass To override something (or pass extra args), do this:...
1
21530577
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/21530577/fatal-error-python-h-no-such-file-or-directory
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
21,530,577
fatal error: Python.h: No such file or directory
1,945
1,987,374
37
true
true
[ "python", "gcc", "python-c-api" ]
2014-02-03T15:00:16
2025-08-29T16:56:33
Mohanad Y.
false
CC BY-SA 4.0
21,548,557
3,266,302
19,788
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: gcc -Wall utilsmodule.c -o Utilc After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory compilation terminated. I ha...
<p>I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below:</p> <pre class="lang-bash prettyprint-override"><code>gcc -Wall utilsmodule.c -o Utilc </code></pre> <p>After executing the command, I get this error message:</p> <pre class="lang-none...
[ { "answerId": 21530768, "score": 3620, "isAccepted": false, "createdAt": "2014-02-03T15:10:01", "ownerDisplayName": "wim", "ownerUserId": 674039, "bodyText": "Looks like you haven't properly installed the header files and static libraries for python dev. Use your package manager to insta...
1
3996904
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/3996904/generate-random-integers-between-0-and-9
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
3,996,904
Generate random integers between 0 and 9
1,931
3,009,154
24
true
true
[ "python", "random", "integer" ]
2010-10-22T12:48:29
2025-03-24T17:05:55
aneuryzm
false
CC BY-SA 4.0
3,996,930
257,022
65,152
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How can I generate random integers between 0 and 9 (inclusive) in Python? For example, 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9
<p>How can I generate random integers between <code>0</code> and <code>9</code> (inclusive) in Python?</p> <p>For example, <code>0</code>, <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, <code>5</code>, <code>6</code>, <code>7</code>, <code>8</code>, <code>9</code></p>
[ { "answerId": 3996930, "score": 2652, "isAccepted": true, "createdAt": "2010-10-22T12:51:31", "ownerDisplayName": "kovshenin", "ownerUserId": 24894, "bodyText": "Try random.randrange : from random import randrange print(randrange(10))" } ]
1
1301346
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,301,346
What is the meaning of single and double underscore before an object name?
1,923
897,612
19
true
true
[ "python", "oop", "naming-conventions", "identifier" ]
2009-08-19T17:11:57
2025-05-12T10:24:37
Ram Rachum
false
CC BY-SA 4.0
1,301,369
76,701
89,955
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
What do single and double leading underscores before an object's name represent in Python?
<p>What do single and double leading underscores before an object's name represent in Python?</p>
null
0
14132789
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
14,132,789
Relative imports for the billionth time
1,905
783,806
17
true
true
[ "python", "python-import", "relative-path", "python-packaging", "relative-import" ]
2013-01-03T03:50:40
2025-03-18T06:56:38
user1881400
false
CC BY-SA 4.0
14,132,912
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I've been here: PEP 328 – Imports: Multi-Line and Absolute/Relative Modules, Packages Python packages: relative imports Python relative import example code does not work Relative imports in Python 2.5 Relative imports in Python Python: Disabling relative import and plenty of URLs that I did not copy, some on SO, some o...
<p>I've been here:</p> <ul> <li><em><a href="http://www.python.org/dev/peps/pep-0328/" rel="noreferrer">PEP 328 – Imports: Multi-Line and Absolute/Relative</a></em></li> <li><em><a href="http://docs.python.org/2/tutorial/modules.html#packages" rel="noreferrer">Modules, Packages</a></em></li> <li><a href="https://stacko...
[ { "answerId": 14132912, "score": 2434, "isAccepted": true, "createdAt": "2013-01-03T04:06:37", "ownerDisplayName": "BrenBarn", "ownerUserId": 1427416, "bodyText": "Script vs. Module Here's an explanation. The short version is that there is a big difference between directly running a Pyth...
1
16981921
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/16981921/relative-imports-in-python-3
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
16,981,921
Relative imports in Python 3
1,892
2,222,622
36
true
true
[ "python", "python-3.x", "python-import" ]
2013-06-07T10:26:50
2025-05-11T14:17:43
John Smith Optional
false
CC BY-SA 4.0
16,985,066
1,126,971
25,567
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I want to import a function from another file in the same directory. Usually, one of the following works: from .mymodule import myfunction from mymodule import myfunction ...but the other one gives me one of these errors: ImportError: attempted relative import with no known parent package ModuleNotFoundError: No module...
<p>I want to import a function from another file in the same directory.</p> <p>Usually, one of the following works:</p> <pre><code>from .mymodule import myfunction </code></pre> <pre><code>from mymodule import myfunction </code></pre> <p>...but the other one gives me one of these errors:</p> <pre class="lang-none prett...
null
0
12309269
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
12,309,269
How do I write JSON data to a file?
1,887
3,205,837
19
true
true
[ "python", "json" ]
2012-09-06T22:21:21
2025-04-27T17:24:47
user1530318
false
CC BY-SA 4.0
12,309,296
1,530,318
28,137
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I write JSON data stored in the dictionary data to a file? f = open('data.json', 'wb') f.write(data) This gives the error: TypeError: must be string or buffer, not dict
<p>How do I write JSON data stored in the dictionary <code>data</code> to a file?</p> <pre><code>f = open('data.json', 'wb') f.write(data) </code></pre> <p>This gives the error:</p> <blockquote> <p>TypeError: must be string or buffer, not dict</p> </blockquote>
[ { "answerId": 12309296, "score": 3355, "isAccepted": true, "createdAt": "2012-09-06T22:23:14", "ownerDisplayName": "phihag", "ownerUserId": 35070, "bodyText": "data is a Python dictionary. It needs to be encoded as JSON before writing. Use this for maximum compatibility (Python 2 and 3):...
1
1534210
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1534210/use-a-different-python-version-with-virtualenv
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,534,210
Use a different Python version with virtualenv
1,884
2,576,920
44
true
true
[ "python", "virtualenv", "virtualenvwrapper" ]
2009-10-07T21:11:22
2026-07-03T19:04:35
Ulf
false
CC BY-SA 4.0
1,534,343
51,208
19,550
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I create a virtual environment for a specified version of Python?
<p>How do I create a virtual environment for a specified version of Python?</p>
[ { "answerId": 1534343, "score": 2069, "isAccepted": true, "createdAt": "2009-10-07T21:33:12", "ownerDisplayName": "Daniel Roseman", "ownerUserId": 104349, "bodyText": "NOTE: For Python 3.3+ , see The Aelfinn's answer below. Use the --python (or short -p ) option when creating a virtualen...
1
541390
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/541390/extracting-extension-from-filename
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
541,390
Extracting extension from filename
1,879
1,690,047
33
true
true
[ "python", "filenames", "file-extension" ]
2009-02-12T14:11:50
2025-05-07T12:20:53
Alex
false
CC BY-SA 4.0
541,394
85,185
45,101
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Is there a function to extract the extension from a filename?
<p>Is there a function to extract the extension from a filename?</p>
[ { "answerId": 541394, "score": 2685, "isAccepted": true, "createdAt": "2009-02-12T14:12:46", "ownerDisplayName": "nosklo", "ownerUserId": 17160, "bodyText": "Use os.path.splitext : >>> import os >>> filename, file_extension = os.path.splitext('/path/to/somefile.ext') >>> filename '/path/...
1
67631
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/67631/how-can-i-import-a-module-dynamically-given-the-full-path
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
67,631
How can I import a module dynamically given the full path?
1,877
1,618,475
38
true
true
[ "python", "python-import", "python-module" ]
2008-09-15T22:30:55
2024-02-17T17:55:58
derfred
false
CC BY-SA 4.0
67,692
10,286
20,201
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I load a Python module given its full path? Note that the file can be anywhere in the filesystem where the user has access rights. See also: How to import a module given its name as string?
<p>How do I load a Python module given its full path?</p> <p>Note that the file can be anywhere in the filesystem where the user has access rights.</p> <hr /> <p><sub><strong>See also:</strong> <a href="https://stackoverflow.com/questions/301134">How to import a module given its name as string?</a></sub></p>
null
0
1557571
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1557571/how-do-i-get-time-of-a-python-programs-execution
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,557,571
How do I get time of a Python program's execution?
1,833
2,931,696
41
true
true
[ "python", "time", "execution-time" ]
2009-10-12T23:56:47
2024-12-11T22:04:58
john2x
false
CC BY-SA 4.0
1,557,584
159,685
23,952
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running. I've looked at the timeit module, but it seems it's only for small snippets of code. I want to time the whole program.
<p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p> <p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
[ { "answerId": 1557584, "score": 3122, "isAccepted": true, "createdAt": "2009-10-13T00:00:53", "ownerDisplayName": "rogeriopvl", "ownerUserId": 28388, "bodyText": "The simplest way in Python: import time start_time = time.time() main() print(\"--- %s seconds ---\" % (time.time() - start_t...
1
5574702
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/5574702/how-do-i-print-to-stderr-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
5,574,702
How do I print to stderr in Python?
1,823
1,375,535
17
true
true
[ "python", "printing", "stderr" ]
2011-04-07T00:59:10
2022-10-03T09:36:11
wim
false
CC BY-SA 4.0
14,981,125
674,039
370,110
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
There are several ways to write to stderr: print >> sys.stderr, "spam" # Python 2 only. sys.stderr.write("spam\n") os.write(2, b"spam\n") from __future__ import print_function print("spam", file=sys.stderr) What are the differences between these methods? Which method should be preferred?
<p>There are several ways to write to stderr:</p> <pre><code>print &gt;&gt; sys.stderr, &quot;spam&quot; # Python 2 only. sys.stderr.write(&quot;spam\n&quot;) os.write(2, b&quot;spam\n&quot;) from __future__ import print_function print(&quot;spam&quot;, file=sys.stderr) </code></pre> <p>What are the differences bet...
null
0
2257441
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
2,257,441
Random string generation with upper case letters and digits
1,823
1,550,387
36
true
true
[ "python", "string", "random" ]
2010-02-13T12:23:58
2024-08-19T13:20:11
Hellnar
false
CC BY-SA 4.0
2,257,449
151,937
65,513
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I generate a string of size N, made of numbers and uppercase English letters such as: 6U1S75 4Z4UKK U911K4
<p>How do I generate a string of size N, made of numbers and uppercase English letters such as:</p> <ul> <li>6U1S75</li> <li>4Z4UKK</li> <li>U911K4</li> </ul>
[ { "answerId": 2257449, "score": 3313, "isAccepted": true, "createdAt": "2010-02-13T12:26:22", "ownerDisplayName": "Ignacio Vazquez-Abrams", "ownerUserId": 20862, "bodyText": "Answer in one line: ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) or even shor...
1
6760685
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/6760685/what-is-the-best-way-of-implementing-a-singleton-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
6,760,685
What is the best way of implementing a singleton in Python?
1,812
856,747
44
true
true
[ "best-practices", "python", "singleton", "metaclass", "base-class" ]
2011-07-20T10:47:57
2026-07-13T12:59:40
theheadofabroom
false
CC BY-SA 4.0
73,988,733
655,372
22,585
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I have multiple classes which would become singletons (my use case is for a logger, but this is not important). I do not wish to clutter several classes with added gumph when I can simply inherit or decorate. Best methods: Method 1: A decorator def singleton(class_): instances = {} def getinstance(*args, **kwargs): if ...
<p>I have multiple classes which would become singletons (my use case is for a logger, but this is not important). I do not wish to clutter several classes with added gumph when I can simply inherit or decorate.</p> <p>Best methods:</p> <hr /> <h2>Method 1: A decorator</h2> <pre><code>def singleton(class_): instanc...
null
0
44834
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/44834/what-does-all-mean-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
44,834
What does __all__ mean in Python?
1,809
747,521
10
true
true
[ "python", "syntax", "namespaces", "python-import" ]
2008-09-04T21:28:18
2025-03-27T14:46:39
varikin
false
CC BY-SA 4.0
44,842
1,794
18,483
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I see __all__ in __init__.py files. What does it do?
<p>I see <code>__all__</code> in <code>__init__.py</code> files. What does it do?</p>
null
0
9622163
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/9622163/save-plot-to-image-file-instead-of-displaying-it
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
9,622,163
Save plot to image file instead of displaying it
1,807
3,273,678
25
true
true
[ "python", "matplotlib", "savefig" ]
2012-03-08T17:38:10
2024-08-14T16:36:23
Homunculus Reticulli
false
CC BY-SA 4.0
9,890,599
962,891
69,274
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
This displays the figure in a GUI: import matplotlib.pyplot as plt plt.plot([1, 2, 3], [1, 4, 9]) plt.show() But how do I instead save the figure to a file (e.g. foo.png)?
<p>This displays the figure in a GUI:</p> <pre><code>import matplotlib.pyplot as plt plt.plot([1, 2, 3], [1, 4, 9]) plt.show() </code></pre> <p>But how do I instead save the figure to a file (e.g. foo.png)?</p>
[ { "answerId": 9890599, "score": 2302, "isAccepted": true, "createdAt": "2012-03-27T13:35:44", "ownerDisplayName": "Hooked", "ownerUserId": 249341, "bodyText": "When using matplotlib.pyplot.savefig , the file format can be specified by the extension: from matplotlib import pyplot as plt p...
1
11285613
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/11285613/selecting-multiple-columns-in-a-pandas-dataframe
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
11,285,613
Selecting multiple columns in a Pandas dataframe
1,801
4,276,842
22
true
true
[ "python", "pandas", "dataframe", "select", "indexing" ]
2012-07-01T21:03:16
2023-11-03T23:33:47
user1234440
false
CC BY-SA 4.0
11,287,278
1,610,626
23,777
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I select columns a and b from df , and save them into a new dataframe df1 ? index a b c 1 2 3 4 2 3 4 5 Unsuccessful attempt: df1 = df['a':'b'] df1 = df.ix[:, 'a':'b']
<p>How do I select columns <code>a</code> and <code>b</code> from <code>df</code>, and save them into a new dataframe <code>df1</code>?</p> <pre class="lang-none prettyprint-override"><code>index a b c 1 2 3 4 2 3 4 5 </code></pre> <p>Unsuccessful attempt:</p> <pre class="lang-py prettyprint-over...
[ { "answerId": 11287278, "score": 2743, "isAccepted": true, "createdAt": "2012-07-02T02:43:02", "ownerDisplayName": "ely", "ownerUserId": 567620, "bodyText": "The column names (which are strings) cannot be sliced in the manner you tried. Here you have a couple of options. If you know from...
1
209840
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/209840/make-a-dictionary-dict-from-separate-lists-of-keys-and-values
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
209,840
Make a dictionary (dict) from separate lists of keys and values
1,798
1,425,930
22
true
true
[ "python", "list", "dictionary", "key" ]
2008-10-16T19:05:47
2025-03-25T19:53:42
Guido
false
CC BY-SA 4.0
209,854
12,388
47,955
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'} How can I do this?
<p>I want to combine these:</p> <pre class="lang-py prettyprint-override"><code>keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] </code></pre> <p>into a single dictionary:</p> <pre class="lang-py prettyprint-override"><code>{'name': 'Monty', 'age': 42, 'food': 'spam'} </code></pre> <p>How can I do this?</p...
[ { "answerId": 209854, "score": 3000, "isAccepted": true, "createdAt": "2008-10-16T19:09:05", "ownerDisplayName": "Dan Lenski", "ownerUserId": 20789, "bodyText": "Like this: keys = ['a', 'b', 'c'] values = [1, 2, 3] dictionary = dict(zip(keys, values)) print(dictionary) # {'a': 1, 'b': 2,...
1
678236
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/678236/how-do-i-get-the-filename-without-the-extension-from-a-path-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
678,236
How do I get the filename without the extension from a path in Python?
1,793
2,410,574
33
true
true
[ "python", "string", "path" ]
2009-03-24T16:41:03
2025-05-07T15:31:47
Joan Venge
false
CC BY-SA 4.0
678,242
51,816
334,709
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I get the filename without the extension from a path in Python? "/path/to/some/file.txt" → "file"
<p>How do I get the filename without the extension from a path in Python?</p> <pre><code>&quot;/path/to/some/file.txt&quot; → &quot;file&quot; </code></pre>
[ { "answerId": 678242, "score": 1943, "isAccepted": true, "createdAt": "2009-03-24T16:43:15", "ownerDisplayName": "Geo", "ownerUserId": 31610, "bodyText": "Python 3.4+ Use pathlib.Path.stem >>> from pathlib import Path >>> Path(\"/path/to/file.txt\").stem 'file' >>> Path(\"/path/to/file.t...
1
582336
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/582336/how-do-i-profile-a-python-script
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
582,336
How do I profile a Python script?
1,762
963,808
34
true
true
[ "python", "performance", "optimization", "time-complexity", "profiling" ]
2009-02-24T16:01:26
2024-07-17T07:12:07
Chris Lawlor
false
CC BY-SA 4.0
582,337
21,245
49,652
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With Python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to __main__ . What is a good way to profile how long a Python program takes to run?
<p><a href="http://en.wikipedia.org/wiki/Project_Euler" rel="noreferrer">Project Euler</a> and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With Python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>...
[ { "answerId": 582337, "score": 1829, "isAccepted": true, "createdAt": "2009-02-24T16:01:40", "ownerDisplayName": "Chris Lawlor", "ownerUserId": 21245, "bodyText": "Python includes a profiler called cProfile . It not only gives the total running time, but also times each function separate...
1
4260280
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
4,260,280
if/else in a list comprehension
1,748
2,236,060
13
true
true
[ "python", "list", "if-statement", "list-comprehension" ]
2010-11-23T19:56:44
2025-03-27T14:50:01
AP257
false
CC BY-SA 4.0
4,260,304
267,831
95,081
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I convert the following for -loop containing an if / else into a list comprehension? results = [] for x in xs: results.append(f(x) if x is not None else '') It should yield '' if x is None , and otherwise f(x) . I tried: [f(x) for x in xs if x is not None else ''] but it gives a SyntaxError . What is the correct...
<p>How do I convert the following <code>for</code>-loop containing an <code>if</code>/<code>else</code> into a list comprehension?</p> <pre><code>results = [] for x in xs: results.append(f(x) if x is not None else '') </code></pre> <p>It should yield <code>''</code> if <code>x</code> is <code>None</code>, and other...
[ { "answerId": 4260304, "score": 2927, "isAccepted": true, "createdAt": "2010-11-23T19:59:17", "ownerDisplayName": "poke", "ownerUserId": 216074, "bodyText": "You can totally do that. It's just an ordering issue: [f(x) if x is not None else '' for x in xs] In general, [f(x) if condition e...
1
944700
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/944700/how-to-check-for-nan-values
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
944,700
How to check for NaN values
1,729
3,204,757
21
true
true
[ "python", "math", "nan" ]
2009-06-03T13:19:54
2024-11-02T11:37:43
Jack Ha
false
CC BY-SA 4.0
944,733
80,500
21,251
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
float('nan') represents NaN (not a number). But how do I check for it?
<p><code>float('nan')</code> represents NaN (not a number). But how do I check for it?</p>
[ { "answerId": 944733, "score": 2214, "isAccepted": true, "createdAt": "2009-06-03T13:24:37", "ownerDisplayName": "gimel", "ownerUserId": 6491, "bodyText": "Use math.isnan : >>> import math >>> x = float('nan') >>> math.isnan(x) True" } ]
1
4700614
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/4700614/how-to-put-the-legend-outside-the-plot
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
4,700,614
How to put the legend outside the plot
1,728
2,154,060
18
true
true
[ "python", "matplotlib", "seaborn", "legend" ]
2011-01-15T16:10:03
2026-02-12T22:36:28
pottigopi
false
CC BY-SA 4.0
4,700,674
576,840
17,289
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. I want to keep the legend box outside the plot area (I want the legend to be outside at the right side of the ...
<p>I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced.</p> <ol> <li>I want to keep the legend box outside the plot area (I want the legend to be outside at the ri...
[ { "answerId": 4701285, "score": 2518, "isAccepted": false, "createdAt": "2011-01-15T18:12:27", "ownerDisplayName": "Joe Kington", "ownerUserId": 325565, "bodyText": "There are a number of ways to do what you want. To add to what Christian Alis and Navi already said , you can use the bbox...
2
4015417
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/4015417/why-do-python-classes-inherit-object
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
4,015,417
Why do Python classes inherit object?
1,717
469,076
6
true
true
[ "python", "class", "oop", "object", "inheritance" ]
2010-10-25T14:15:26
2022-04-09T07:21:43
tjvr
false
CC BY-SA 4.0
45,062,077
359,640
18,071
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Why does the following class declaration inherit from object ? class MyClass(object): ...
<p>Why does the following class declaration inherit from <code>object</code>?</p> <pre><code>class MyClass(object): ... </code></pre>
[ { "answerId": 45062077, "score": 1265, "isAccepted": true, "createdAt": "2017-07-12T15:34:59", "ownerDisplayName": "Dimitris Fasarakis Hilliard", "ownerUserId": 4952130, "bodyText": "Is there any reason for a class declaration to inherit from object ? In Python 3, apart from compatibilit...
1
60208
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
60,208
Replacements for switch statement in Python?
1,716
2,361,363
44
true
true
[ "python", "switch-statement" ]
2008-09-13T00:36:30
2025-02-22T04:31:39
Michael Schneider
false
CC BY-SA 4.0
60,211
4,907
17,968
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I want to write a function in Python that returns different fixed values based on the value of an input index. In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
[ { "answerId": 60211, "score": 2247, "isAccepted": true, "createdAt": "2008-09-13T00:38:24", "ownerDisplayName": "Greg Hewgill", "ownerUserId": 893, "bodyText": "Python 3.10 (2021) introduced the match - case statement, which provides a first-class implementation of a \"switch\" for Pytho...
2
931092
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/931092/how-do-i-reverse-a-string-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
931,092
How do I reverse a string in Python?
1,714
1,756,936
14
true
true
[ "python", "string" ]
2009-05-31T02:10:10
2023-12-23T07:11:28
oneself
false
CC BY-SA 4.0
931,095
9,435
40,949
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
There is no built in reverse method for Python's str object. How can I reverse a string?
<p>There is no built in <code>reverse</code> method for Python's <code>str</code> object. How can I reverse a string?</p>
[ { "answerId": 931095, "score": 3168, "isAccepted": true, "createdAt": "2009-05-31T02:11:46", "ownerDisplayName": "Paolo Bergantino", "ownerUserId": 16417, "bodyText": "Using slicing : >>> 'hello world'[::-1] 'dlrow olleh' Slice notation takes the form [start:stop:step] . In this case, we...
1
8933237
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/8933237/how-do-i-check-if-a-directory-exists-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
8,933,237
How do I check if a directory exists in Python?
1,682
1,795,935
16
true
true
[ "python", "directory" ]
2012-01-19T21:03:20
2026-05-12T09:45:02
David542
false
CC BY-SA 4.0
8,933,290
651,174
112,952
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I check if a directory exists in Python?
<p>How do I check if a directory exists in Python?</p>
[ { "answerId": 8933290, "score": 2445, "isAccepted": true, "createdAt": "2012-01-19T21:07:25", "ownerDisplayName": "phihag", "ownerUserId": 35070, "bodyText": "Use os.path.isdir for directories only: >>> import os >>> os.path.isdir('new_folder') True Use os.path.exists for both files and ...
1
1471994
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1471994/what-is-setup-py
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,471,994
What is setup.py?
1,657
1,308,666
10
true
true
[ "python", "pypi", "setup.py", "python-packaging" ]
2009-09-24T14:16:52
2025-09-16T06:39:45
Software Enthusiastic
false
CC BY-SA 4.0
1,472,014
97,526
26,693
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
What is setup.py and how can it be configured or used?
<p>What is <code>setup.py</code> and how can it be configured or used?</p>
[ { "answerId": 1472014, "score": 1229, "isAccepted": true, "createdAt": "2009-09-24T14:19:35", "ownerDisplayName": "Silfverstrom", "ownerUserId": 54736, "bodyText": "setup.py is a Python file, the presence of which is an indication that the module/package you are about to install has like...
1
7943751
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/7943751/what-is-the-python-3-equivalent-of-python-m-simplehttpserver
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
7,943,751
What is the Python 3 equivalent of "python -m SimpleHTTPServer"
1,653
851,729
7
true
true
[ "python", "python-3.x", "httpserver", "simplehttpserver" ]
2011-10-30T07:22:49
2022-02-22T06:55:42
ryanbraganza
false
CC BY-SA 4.0
7,943,768
845,948
17,263
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
What is the Python 3 equivalent of python -m SimpleHTTPServer ?
<p>What is the Python 3 equivalent of <code>python -m SimpleHTTPServer</code>?</p>
[ { "answerId": 7943768, "score": 2307, "isAccepted": true, "createdAt": "2011-10-30T07:28:58", "ownerDisplayName": "Petr Viktorin", "ownerUserId": 99057, "bodyText": "From the docs : The SimpleHTTPServer module has been merged into http.server in Python 3.0. The 2to3 tool will automatical...
1
230751
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/230751/how-can-i-flush-the-output-of-the-print-function
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
230,751
How can I flush the output of the print function?
1,646
1,209,293
14
true
true
[ "python", "printing", "flush", "output-buffering" ]
2008-10-23T17:59:39
2024-03-21T09:13:14
Walter Nissen
false
CC BY-SA 4.0
230,774
8,835
17,227
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I force Python's print function to flush the buffered output to the screen? See also: Disable output buffering if the goal is to change the buffering behaviour generally. This question is about explicitly flushing output after a specific print call, even though output is still being buffered. For duplicate close...
<p>How do I force Python's <code>print</code> function to flush the buffered output to the screen?</p> <hr /> <p><sub><strong>See also:</strong> <a href="https://stackoverflow.com/questions/107705">Disable output buffering</a> if the goal is to change the buffering behaviour generally. This question is about explicitly...
[ { "answerId": 230774, "score": 1959, "isAccepted": true, "createdAt": "2008-10-23T18:04:59", "ownerDisplayName": "CesarB", "ownerUserId": 28258, "bodyText": "In Python 3, print can take an optional flush argument: print(\"Hello, World!\", flush=True) In Python 2, after calling print , do...
1
3702675
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/3702675/catch-and-print-full-python-exception-traceback-without-halting-exiting-the-prog
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
3,702,675
Catch and print full Python exception traceback without halting/exiting the program
1,626
1,860,013
19
true
true
[ "python", "exception", "try-catch", "traceback" ]
2010-09-13T17:03:30
2024-12-05T09:33:21
chriscauley
false
CC BY-SA 4.0
16,946,886
266,564
21,681
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I want to catch and log exceptions without exiting, e.g., try: do_stuff() except Exception as err: print(Exception, err) # I want to print the entire traceback here, # not just the exception name and details I want to print the exact same output that is printed when the exception is raised without the try/except interc...
<p>I want to catch and log exceptions without exiting, e.g.,</p> <pre><code>try: do_stuff() except Exception as err: print(Exception, err) # I want to print the entire traceback here, # not just the exception name and details </code></pre> <p>I want to print the exact same output that is printed when th...
[ { "answerId": 3702847, "score": 1530, "isAccepted": false, "createdAt": "2010-09-13T17:27:26", "ownerDisplayName": "volting", "ownerUserId": 252701, "bodyText": "traceback.format_exc() will yield more info if that's what you want. import traceback def do_stuff(): raise Exception(\"test e...
1
1747817
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1747817/create-a-dictionary-with-comprehension
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,747,817
Create a dictionary with comprehension
1,614
1,254,758
17
true
true
[ "python", "dictionary", "list-comprehension", "dictionary-comprehension" ]
2009-11-17T10:07:53
2023-09-12T13:26:51
flybywire
false
CC BY-SA 4.0
1,747,827
63,051
277,632
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Can I use list comprehension syntax to create a dictionary? For example, by iterating over pairs of keys and values: d = {... for k, v in zip(keys, values)}
<p>Can I use list comprehension syntax to create a dictionary?</p> <p>For example, by iterating over pairs of keys and values:</p> <pre><code>d = {... for k, v in zip(keys, values)} </code></pre>
[ { "answerId": 1747827, "score": 2368, "isAccepted": true, "createdAt": "2009-11-17T10:09:32", "ownerDisplayName": "fortran", "ownerUserId": 106979, "bodyText": "Use a dict comprehension (Python 2.7 and later): {key: value for key, value in zip(keys, values)} Alternatively, use the dict c...
1
3394835
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
3,394,835
Use of *args and **kwargs
1,599
995,807
11
true
true
[ "python", "args", "keyword-argument" ]
2010-08-03T08:28:07
2021-07-29T20:26:33
MacPython
true
null
3,394,898
337,247
18,499
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
So I have difficulty with the concept of *args and **kwargs . So far I have learned that: *args = list of arguments - as positional arguments **kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments. I don't understand what programming task this would be helpf...
<p>So I have difficulty with the concept of <code>*args</code> and <code>**kwargs</code>.</p> <p>So far I have learned that:</p> <ul> <li><code>*args</code> = list of arguments - as positional arguments</li> <li><code>**kwargs</code> = dictionary - whose keys become separate keyword arguments and the values become va...
[ { "answerId": 3394898, "score": 1832, "isAccepted": true, "createdAt": "2010-08-03T08:38:45", "ownerDisplayName": "David Webb", "ownerUserId": 3171, "bodyText": "The syntax is the * and ** . The names *args and **kwargs are only by convention but there's no hard requirement to use them. ...
1
961632
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/961632/convert-integer-to-string-in-python
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
961,632
Convert integer to string in Python
1,596
3,896,982
14
true
true
[ "python", "string", "integer" ]
2009-06-07T10:22:38
2024-12-17T14:48:15
Hick
false
CC BY-SA 4.0
961,638
105,167
36,624
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I convert an integer to a string? 42 ⟶ "42" For the reverse, see How do I parse a string to a float or int? . Floats can be handled similarly, but handling the decimal points can be tricky because floating-point values are not precise . See Converting a float to a string without rounding it for more specific adv...
<p>How do I convert an integer to a string?</p> <pre><code>42 ⟶ &quot;42&quot; </code></pre> <hr /> <p><sub>For the reverse, see <a href="https://stackoverflow.com/questions/379906/">How do I parse a string to a float or int?</a>. Floats can be handled similarly, but handling the decimal points can be tricky becaus...
[ { "answerId": 961638, "score": 2358, "isAccepted": true, "createdAt": "2009-06-07T10:24:15", "ownerDisplayName": "Bastien Léonard", "ownerUserId": 88851, "bodyText": ">>> str(42) '42' >>> int('42') 42 Links to the documentation: int() str() str(x) converts any object x to a string by cal...
1
9001509
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/9001509/how-do-i-sort-a-dictionary-by-key
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
9,001,509
How do I sort a dictionary by key?
1,587
2,450,419
33
true
true
[ "python", "sorting", "dictionary" ]
2012-01-25T10:54:29
2026-03-09T08:42:57
Antony
false
CC BY-SA 4.0
9,001,529
1,069,533
16,497
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
How do I sort a dictionary by its keys? Example input: {2:3, 1:89, 4:5, 3:0} Desired output: {1:89, 2:3, 3:0, 4:5}
<p>How do I sort a dictionary by its keys?</p> <p>Example input:</p> <pre><code>{2:3, 1:89, 4:5, 3:0} </code></pre> <p>Desired output:</p> <pre><code>{1:89, 2:3, 3:0, 4:5} </code></pre>
[ { "answerId": 9001529, "score": 1325, "isAccepted": true, "createdAt": "2012-01-25T10:56:30", "ownerDisplayName": "NPE", "ownerUserId": 367273, "bodyText": "Note: for Python 3.7+, see this answer Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,v...
1
15891038
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/15891038/change-column-type-in-pandas
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
15,891,038
Change column type in pandas
1,585
4,252,751
16
true
true
[ "python", "pandas", "dataframe", "types", "type-conversion" ]
2013-04-08T23:53:30
2024-07-09T21:49:17
user1642513
false
CC BY-SA 4.0
28,648,923
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
I created a DataFrame from a list of lists: table = [ ['a', '1.2', '4.2' ], ['b', '70', '0.03'], ['x', '5', '0' ], ] df = pd.DataFrame(table) How do I convert the columns to specific types? In this case, I want to convert columns 2 and 3 into floats. Is there a way to specify the types while converting the list to Data...
<p>I created a DataFrame from a list of lists:</p> <pre class="lang-py prettyprint-override"><code>table = [ ['a', '1.2', '4.2' ], ['b', '70', '0.03'], ['x', '5', '0' ], ] df = pd.DataFrame(table) </code></pre> <p>How do I convert the columns to specific types? In this case, I want to convert co...
[ { "answerId": 28648923, "score": 2642, "isAccepted": true, "createdAt": "2015-02-21T17:37:02", "ownerDisplayName": "Alex Riley", "ownerUserId": 3923281, "bodyText": "You have four main options for converting types in pandas: to_numeric() - provides functionality to safely convert non-num...
1
1549801
question
stackoverflow
2026-08-03T01:37:29
null
null
null
null
null
https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance
OcN7A9CDxbrWVwaw5
unPv1LuxmpaTYkIgE
1,549,801
What are the differences between type() and isinstance()?
1,577
922,236
8
true
true
[ "python", "oop", "inheritance", "types" ]
2009-10-11T03:50:54
2023-09-13T08:33:28
abbot
true
null
1,549,854
4,001
27,986
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
What are the differences between these two code snippets? Using type : import types if type(a) is types.DictType: do_something() if type(b) in types.StringTypes: do_something_else() Using isinstance : if isinstance(a, dict): do_something() if isinstance(b, str) or isinstance(b, unicode): do_something_else()
<p>What are the differences between these two code snippets?</p> <p>Using <a href="https://docs.python.org/3/library/functions.html#type" rel="noreferrer"><code>type</code></a>:</p> <pre><code>import types if type(a) is types.DictType: do_something() if type(b) in types.StringTypes: do_something_else() </code>...
[ { "answerId": 1549854, "score": 1557, "isAccepted": true, "createdAt": "2009-10-11T04:31:57", "ownerDisplayName": "Alex Martelli", "ownerUserId": 95810, "bodyText": "To summarize the contents of other (already good!) answers, isinstance caters for inheritance (an instance of a derived cl...
1