Questions tagged [python]
Python is a multi-paradigm, dynamically typed, multipurpose programming language. It is designed to be quick to learn, understand, and use, and enforces a clean and uniform syntax. Please note that Python 2 is officially out of support as of 01-01-2020. Still, for version-specific Python questions, add the [python-2.7] or [python-3.x] tag. When using a Python variant (e.g., Jython, PyPy) or library (e.g., Pandas and NumPy), please include it in the tags.
What is the use of the yield keyword in Python? What does it do?
For example, I'm trying to understand this code1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild ...
asked Oct 23 '08 at 22:21
Alex. S.
129k1616 gold badges5050 silver badges6161 bronze badges
Given the following code, what does the if __name__ == "__main__": do?
# Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while True:
lock.acquire()
...
asked Jan 7 '09 at 4:11
Devoted
91.9k4141 gold badges8585 silver badges110110 bronze badges
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
In Python, what are metaclasses and what do we use them for?
asked Sep 19 '08 at 6:10
e-satis
524k103103 gold badges283283 silver badges322322 bronze badges
How do I check whether a file exists or not, without using the try statement?
asked Sep 17 '08 at 12:55
spence91
69k88 gold badges2525 silver badges1919 bronze badges
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The update() method would be what I need, if it returned ...
asked Sep 2 '08 at 7:44
Carl Meyer
108k1818 gold badges102102 silver badges113113 bronze badges
How do you call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
asked Sep 18 '08 at 1:35
freshWoWer
55.8k1010 gold badges3232 silver badges3333 bronze badges
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:
import os
file_path = "/my/...
asked Nov 7 '08 at 18:56
Parand
92.9k4343 gold badges148148 silver badges182182 bronze badges
How do I access the index in a for loop like the following?
ints = [8, 23, 45, 12, 78]
for i in ints:
print('item #{} = {}'.format(???, i))
I want to get this output:
item #1 = 8
item #2 = 23
...
asked Feb 6 '09 at 22:47
Joan Venge
275k202202 gold badges442442 silver badges657657 bronze badges
Is there a shortcut to make a simple list out of a list of lists in Python?
I can do it in a for loop, but is there some cool "one-liner"?
I tried it with functools.reduce():
from functools ...
asked Jun 4 '09 at 20:30
Emma
42.7k44 gold badges1717 silver badges1010 bronze badges
What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
asked Sep 25 '08 at 21:01
Daryl Spitzer
124k7575 gold badges151151 silver badges168168 bronze badges
I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it....
asked Feb 3 '09 at 22:31
Simon
71.6k2525 gold badges8383 silver badges117117 bronze badges
Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index (1) in Python?
asked Oct 7 '08 at 1:39
Eugene M
41.5k1414 gold badges3535 silver badges4343 bronze badges
I am a bit puzzled by the following code:
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print (key, 'corresponds to', d[key])
What I don't understand is the key portion. How does Python recognize ...
asked Jul 20 '10 at 22:27
TopChef
37.6k1010 gold badges2626 silver badges2727 bronze badges
I'm looking for a string.contains or string.indexof method in Python.
I want to do:
if not somestring.contains("blah"):
continue
asked Aug 9 '10 at 2:52
Blankman
239k300300 gold badges721721 silver badges11311131 bronze badges
How can I list all files of a directory in Python and add them to a list?
asked Jul 8 '10 at 19:31
duhhunjonn
43.1k1111 gold badges2626 silver badges1515 bronze badges
How can I create or use a global variable in a function?
If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable ...
asked Jan 8 '09 at 5:45
user46646
136k4343 gold badges7373 silver badges8282 bronze badges
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 ...
asked Mar 5 '09 at 0:49
Gern Blanston
41.8k1919 gold badges4747 silver badges6464 bronze badges
What is the module/method used to get the current time?
asked Jan 6 '09 at 4:54
user46646
136k4343 gold badges7373 silver badges8282 bronze badges
I know that I can do:
try:
# do something that may fail
except:
# do this if ANYTHING goes wrong
I can also do this:
try:
# do something that may fail
except IDontLikeYouException:
#...
asked Jun 24 '11 at 15:55
inspectorG4dget
99.1k2222 gold badges128128 silver badges225225 bronze badges
For example, if passed the following:
a = []
How do I check to see if a is empty?
asked Sep 10 '08 at 6:20
Ray
172k9696 gold badges215215 silver badges201201 bronze badges
What's the difference between the list methods append() and extend()?
asked Oct 31 '08 at 5:55
Claudiu
209k154154 gold badges450450 silver badges656656 bronze badges
What is the difference between __str__ and __repr__ in Python?
asked Sep 17 '09 at 4:27
Casebash
102k8080 gold badges237237 silver badges337337 bronze badges
Is it possible to add a key to a Python dictionary after it has been created?
It doesn't seem to have an .add() method.
asked Jun 21 '09 at 22:07
lfaraone
45.5k1616 gold badges4848 silver badges7070 bronze badges
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]
asked Nov 12 '09 at 7:04
y2k
60.6k2626 gold badges5858 silver badges8484 bronze badges
How do I copy a file in Python?
I couldn't find anything under os.
asked Sep 23 '08 at 19:23
Matt
73.4k2525 gold badges5252 silver badges6464 bronze badges
I'm using this code to get standard output from an external program:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
The ...
asked Mar 3 '09 at 12:23
Tomas Sedovic
35.4k99 gold badges3636 silver badges3030 bronze badges
I would like to know how to put a time delay in a Python script.
asked Feb 4 '09 at 7:04
user46646
136k4343 gold badges7373 silver badges8282 bronze badges
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'
class PassByReference:
def ...
asked Jun 12 '09 at 10:23
David Sykes
44k1717 gold badges6666 silver badges7777 bronze badges
Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
def foo(a=[]):
a.append(5)
return a
Python novices would expect this function to always ...
asked Jul 15 '09 at 18:00
Stefano Borini
128k9191 gold badges279279 silver badges405405 bronze badges
How can I make two decorators in Python that would do the following?
@makebold
@makeitalic
def say():
return "Hello"
...which should return:
"<b><i>Hello</i></b>"
I'm ...
asked Apr 11 '09 at 7:05
Imran
77.4k2323 gold badges9494 silver badges126126 bronze badges
I have a DataFrame from Pandas:
import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
print df
Output:
c1 c2
0 10 100
1 11 110
2 ...
asked May 10 '13 at 7:04
Roman
101k152152 gold badges320320 silver badges427427 bronze badges
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?
asked Apr 10 '10 at 8:49
aF.
59.6k4141 gold badges127127 silver badges193193 bronze badges
What is __init__.py for in a Python source directory?
asked Jan 15 '09 at 20:09
Mat
69.1k3333 gold badges8383 silver badges106106 bronze badges
I'm trying to understand the use of super(). From the looks of it, both child classes can be created, just fine.
I'm curious to know about the actual difference between the following 2 child classes....
asked Feb 23 '09 at 0:30
Mizipzor
46.5k2020 gold badges9292 silver badges136136 bronze badges
In the following method definitions, what does the * and ** do for param2?
def foo(param1, *param2):
def bar(param1, **param2):
asked Aug 31 '08 at 15:04
Todd
28.9k44 gold badges2020 silver badges1313 bronze badges
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 ...
asked Oct 21 '09 at 19:05
Mohan Gulati
28.1k55 gold badges2020 silver badges2020 bronze badges
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 colume_name = some_value
I tried to look at Pandas' documentation, but ...
asked Jun 12 '13 at 17:42
szli
29.2k88 gold badges2828 silver badges3737 bronze badges
pip is a replacement for easy_install. But should I install pip using easy_install on Windows? Is there a better way?
How do I delete a file or folder in Python?
asked Aug 9 '11 at 13:05
Zygimantas
26.6k55 gold badges1717 silver badges2323 bronze badges
How can I raise an exception in Python so that it can later be caught via an except block?
asked Jan 12 '10 at 21:07
TIMEX
221k330330 gold badges730730 silver badges10431043 bronze badges
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second ...
asked Nov 23 '08 at 12:15
jespern
28k33 gold badges2121 silver badges1212 bronze badges
How do you change the size of figure drawn with Matplotlib?
asked Dec 1 '08 at 21:24
tatwright
31.3k66 gold badges1919 silver badges99 bronze badges
In Python, what commands can I use to find:
the current directory (where I was in the terminal when I ran the Python script), and
where the file I am executing is?
asked Feb 28 '11 at 1:51
John Howard
51.8k2121 gold badges4646 silver badges6464 bronze badges
How can I output colored text to the terminal in Python?
asked Nov 13 '08 at 18:58
aboSamoor
25.8k33 gold badges1515 silver badges1010 bronze badges
I set an environment variable that I want to access in my Python application. How do I get its value?
asked Feb 5 '11 at 13:03
Amit Yadav
27.6k66 gold badges3838 silver badges4747 bronze badges
I've got a huge list of date-times like this as strings:
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them ...
asked Jan 21 '09 at 18:00
Oli
219k6161 gold badges207207 silver badges288288 bronze badges
In Python, how can I parse a numeric string like "545.2222" to its corresponding float value, 545.2222? Or parse the string "31" to an integer, 31?
I just want to know how to parse a float str to a ...
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 ...
In Python, how do you get the last element of a list?
asked May 30 '09 at 19:28
Janusz
178k111111 gold badges295295 silver badges366366 bronze badges