title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 494,821 | <p>Go find out how to convert a recursive problem into an iterative one. Should be able to calculate from there.</p>
<p>That's might be the principles that they're trying to get you to learn, especially if this is an Algorithms course.</p>
| 0 | 2009-01-30T07:45:25Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 499,245 | <p>There is lots of information about the Fibonacci Sequence on <a href="http://en.wikipedia.org/wiki/Fibonacci_number">wikipedia</a> and on <a href="http://mathworld.wolfram.com/FibonacciNumber.html">wolfram</a>. A lot more than you may need. Anyway it is a good thing to learn how to use these resources to find (quick... | 153 | 2009-01-31T18:01:14Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 6,498,725 | <pre><code>def fib():
a,b = 1,1
num=eval(input("Please input what Fib number you want to be calculated: "))
num_int=int(num-2)
for i in range (num_int):
a,b=b,a+b
print(b)
</code></pre>
| 2 | 2011-06-27T20:42:31Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 7,872,648 | <p>15 minutes into a tutorial I used when learning Python, it asked the reader to write a program that would calculate a Fibonacci sequence from 3 input numbers (first Fibonacci number, second number, and number at which to stop the sequence). The tutorial had only covered variables, if/thens, and loops up to that poin... | 0 | 2011-10-24T07:53:33Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 15,950,618 | <p>use recursion:</p>
<pre><code>def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
x=input('which fibonnaci do you want?')
print fib(x)
</code></pre>
| 0 | 2013-04-11T13:53:43Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 18,763,575 | <p>Just going through <a href="http://projecteuler.net/problem=2" rel="nofollow">http://projecteuler.net/problem=2</a> this was my take on it</p>
<pre><code># Even Fibonacci numbers
# Problem 2
def get_fibonacci(size):
numbers = [1,2]
while size > len(numbers):
next_fibonacci = numbers[-1]+numbers[... | 0 | 2013-09-12T11:53:24Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 20,169,916 | <pre><code>def fib(x, y, n):
if n < 1:
return x, y, n
else:
return fib(y, x + y, n - 1)
print fib(0, 1, 4)
(3, 5, 0)
#
def fib(x, y, n):
if n > 1:
for item in fib(y, x + y, n - 1):
yield item
yield x, y, n
f = fib(0, 1, 12)
f.next()
(89, 144, 1)
f.next()[0]... | 0 | 2013-11-24T01:09:50Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 21,399,636 | <p>This was a practice assignment that I saw on Khan Academy's Sal on Python Programming: <a href="https://www.khanacademy.org/science/computer-science-subject/computer-science/v/exercise---write-a-fibonacci-function" rel="nofollow">https://www.khanacademy.org/science/computer-science-subject/computer-science/v/exercis... | 0 | 2014-01-28T07:44:16Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 21,507,234 | <p>These all look a bit more complicated than they need to be.
My code is very simple and fast:</p>
<pre><code>def fibonacci(x):
List = []
f = 1
List.append(f)
List.append(f) #because the fibonacci sequence has two 1's at first
while f<=x:
f = List[-1] + List[-2] #says that f = the su... | 3 | 2014-02-02T04:59:00Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 21,607,318 | <p>Canonical Python code to print Fibonacci sequence:</p>
<pre><code>a,b=1,1
while(True):
print a,
a,b=b,a+b # Could also use b=a+b;a=b-a
</code></pre>
<p>For the problem "Print the first Fibonacci number greater than 1000 digits long":</p>
<pre><code>a,b=1,1
i=1
while(len(str(a))<=1000):
i=i+1
a,b=... | 3 | 2014-02-06T15:39:57Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 21,620,473 | <p>Another way of doing it:</p>
<pre><code>a,n=[0,1],10
map(lambda i: reduce(lambda x,y: a.append(x+y),a[-2:]),range(n-2))
</code></pre>
<p>Assigning list to 'a', assigning integer to 'n'
Map and reduce are 2 of three most powerful functions in python. Here map is used just to iterate 'n-2' times.
a[-2:] will get the... | 0 | 2014-02-07T06:05:27Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 21,704,751 | <p>Why not just simply do the following?</p>
<pre><code>x = [1,1]
for i in xrange(10):
x.append(x[-1] + x[-2])
print ', '.join(str(y) for y in x)
</code></pre>
| 5 | 2014-02-11T14:34:53Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 22,258,711 | <p>Maybe this will help</p>
<pre><code>def fibo(n):
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, b + a
return result
</code></pre>
| 0 | 2014-03-07T19:11:55Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 24,846,766 | <h1>Efficient Pythonic generator of the Fibonacci sequence</h1>
<p>I found this question while trying to get the shortest Pythonic generation of this sequence (later realizing I had seen a similar one in a <a href="https://www.python.org/dev/peps/pep-0255/">Python Enhancement Proposal</a>), and I haven't noticed anyon... | 24 | 2014-07-20T02:24:24Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 26,118,289 | <p><strong>Time complexity :</strong> </p>
<p>The caching feature reduces the normal way of calculating Fibonacci series from <strong>O(2^n)</strong> to <strong>O(n)</strong> by eliminating the repeats in the recursive tree of Fibonacci series :</p>
<p><img src="http://i.stack.imgur.com/59Rpw.png" alt="enter image de... | 7 | 2014-09-30T10:14:59Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 27,343,852 | <p>Try this:</p>
<pre><code>def nth_fib(n):
if n == 0:
return 1
elif n == 1:
return 0
else:
return nth_fib(n - 1) + nth_fib(n - 2)
</code></pre>
| 0 | 2014-12-07T14:50:01Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 28,461,205 | <p>based on classic fibonacci sequence and just for the sake of the one-liners</p>
<p>if you just need the number of the index, you can use the reduce
(even if <em>reduce</em> it's not best suited for this it can be a good exercise)</p>
<pre><code>def fibonacci(index):
return reduce(lambda r,v: r.append(r[-1]+r[-... | 0 | 2015-02-11T18:01:18Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 28,659,265 | <p>How about this one? I guess it's not as fancy as the other suggestions because it demands the initial specification of the previous result to produce the expected output, but I feel is a very readable option, i.e., all it does is to provide the result and the previous result to the recursion.</p>
<pre><code>#count ... | 0 | 2015-02-22T14:58:04Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 33,292,276 | <p>Basically translated from Ruby:</p>
<pre><code>def fib(n):
a = 0
b = 1
for i in range(1,n+1):
c = a + b
print c
a = b
b = c
</code></pre>
<p>... </p>
| 1 | 2015-10-22T23:09:13Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 33,459,246 | <p>OK.. after being tired of referring all lengthy answers, now find the below sort & sweet, pretty straight forward way for implementing Fibonacci in python. You can enhance it it the way you want by getting an argument or getting user inputâ¦or change the limits from 10000. As you needâ¦â¦</p>
<pre><code>def ... | 1 | 2015-11-01T04:35:36Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 33,679,701 | <pre><code>def fib(lowerbound, upperbound):
x = 0
y = 1
while x <= upperbound:
if (x >= lowerbound):
yield x
x, y = y, x + y
startNumber = 10
endNumber = 100
for fib_sequence in fib(startNumber, endNumber):
print "And the next number is... %d!" % fib_sequence
</code></... | 1 | 2015-11-12T19:29:58Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 34,328,275 | <p>A more detailed explanation of how Memoization works for Fibonacci sequence.</p>
<pre><code># Fibonacci sequence Memoization
fib_cache = {0:0, 1:1}
def fibonacci(n):
if n < 0:
return -1
if fib_cache.has_key(n):
print "Fibonacci sequence for %d = %d cached" % (n, fib_cache[n])
re... | 0 | 2015-12-17T06:47:27Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 34,541,746 | <p>I was trying to avoid a recursive function to solve this problem, so I took an iterative approach. I was originally doing a memoized recursive function but kept hitting max recursive depth. I also had strict memory goals so you will see me keeping the array as small as I can during the looping process only keeping ... | 0 | 2015-12-31T05:51:31Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 35,983,856 | <p>Fibonacci sequence is: <code>1, 1, 2, 3, 5, 8, ...</code>.</p>
<p>That is <code>f(1) = 1</code>, <code>f(2) = 1</code>, <code>f(3) = 2</code>, <code>...</code>, <code>f(n) = f(n-1) + f(n-2)</code>. </p>
<p>My favorite implementation (simplest and yet achieves a light speed in compare to other implementations) is t... | 0 | 2016-03-14T09:33:26Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 37,585,674 | <p>This is quite efficient, using O(log n) basic arithmetic operations.</p>
<pre><code>def fib(n):
return pow(2 << n, n + 1, (4 << 2*n) - (2 << n) - 1) % (2 << n)
</code></pre>
<p>This one uses O(1) basic arithmetic operations, but the size of the intermediate results is large and so is no... | 0 | 2016-06-02T07:47:03Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 38,985,626 | <p>I made a slightly interactive python Fibonacci Sequence, it asks how many times you want it to repeat, then it shows you the numbers of the Fibonacci Sequence.
<strong><em>HERE IS THE CODE</em></strong>!!!</p>
<pre><code> while True:
number_1 = 1
number_2 = 1
how_many_times_do_you_want_this_done = inpu... | 0 | 2016-08-16T22:47:45Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 39,214,599 | <p>Recursion adds time. To eliminate loops, first <code>import math</code>. Then use <code>math.sqrt</code> and golden ratio in a function:</p>
<pre><code>#!/usr/bin/env python3
import math
def fib(n):
gr = (1 + math.sqrt(5)) / 2
fib_first = (gr**n - (1 - gr)**n) / math.sqrt(5)
return int(round(fib_first... | 0 | 2016-08-29T20:23:11Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 39,277,476 | <p>this is an improvement to mathew henry's answer:</p>
<pre><code>def fib(n):
a = 0
b = 1
for i in range(1,n+1):
c = a + b
print b
a = b
b = c
</code></pre>
<p>the code should print b instead of printing c</p>
<p>output: 1,1,2,3,5 ....</p>
| 1 | 2016-09-01T17:21:27Z | [
"python",
"fibonacci",
"sequences"
] |
How to write the Fibonacci Sequence in Python | 494,594 | <p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20... | 68 | 2009-01-30T05:49:13Z | 39,613,079 | <p><strong>there is a very easy method to realize taht!</strong> </p>
<p>you can this code online freely by using <a href="http://www.learnpython.org/" rel="nofollow">http://www.learnpython.org/</a></p>
<pre><code># Set the variable brian on line 3!
def fib(n):
"""This is documentation string for function. It'll be ... | 0 | 2016-09-21T09:48:48Z | [
"python",
"fibonacci",
"sequences"
] |
Create a cross-platform protocol helper that runs a python script | 494,769 | <p>I'd like to register a protocol handler, like "myapp:", across OS X, Linux, and Windows, so that when someone clicks a url like "myapp://some/params" in a web browser, a python script will be called and passed in those params.</p>
<p>Obviously this would require something being installed on each machine to enable i... | 6 | 2009-01-30T07:16:22Z | 495,470 | <p>Are you talking about a browser plug-in? If so, which browsers? </p>
<p>Firefox? https://addons.mozilla.org/en-US/firefox/addon/6710</p>
<p>Epiphany? <a href="http://pyconuk.org/talk_abstracts.html" rel="nofollow">http://pyconuk.org/talk_abstracts.html</a> has a reference to extending Epiphany with Python.</p>
... | 0 | 2009-01-30T13:20:41Z | [
"python",
"url",
"cross-platform"
] |
refactor this dictionary-to-xml converter in python | 494,881 | <p>It's a small thing, really: I have this function that converts dict objects to xml.</p>
<p>Here's the function:</p>
<pre><code>def dictToXml(d):
from xml.sax.saxutils import escape
def unicodify(o):
if o is None:
return u'';
return unicode(o)
lines = []
def addDict(nod... | 3 | 2009-01-30T08:33:12Z | 494,890 | <p>Here is my short sketch for a solution:
have a general <code>addSomething()</code> function that dispatches based on the type of the value to <code>addDict()</code>, <code>addList()</code> or <code>addElse()</code>. Those functions recursively call <code>addSomething()</code> again.</p>
<p>Basically you are factori... | 0 | 2009-01-30T08:43:22Z | [
"python",
"xml",
"dry"
] |
refactor this dictionary-to-xml converter in python | 494,881 | <p>It's a small thing, really: I have this function that converts dict objects to xml.</p>
<p>Here's the function:</p>
<pre><code>def dictToXml(d):
from xml.sax.saxutils import escape
def unicodify(o):
if o is None:
return u'';
return unicode(o)
lines = []
def addDict(nod... | 3 | 2009-01-30T08:33:12Z | 494,897 | <p>I noticed you have commonality in adding items. Using this commonality I would refactor adding an item to a separate function.</p>
<pre><code>def addItem(item, name, offset):
if isinstance(item, dict):
lines.append(offset + u"<%s>" % name)
addDict(item, offset + u" " ... | 4 | 2009-01-30T08:48:38Z | [
"python",
"xml",
"dry"
] |
refactor this dictionary-to-xml converter in python | 494,881 | <p>It's a small thing, really: I have this function that converts dict objects to xml.</p>
<p>Here's the function:</p>
<pre><code>def dictToXml(d):
from xml.sax.saxutils import escape
def unicodify(o):
if o is None:
return u'';
return unicode(o)
lines = []
def addDict(nod... | 3 | 2009-01-30T08:33:12Z | 494,905 | <pre><code>>>> from pyfo import pyfo
>>> d = ('site', { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } )
>>> result = pyfo(d, pretty=True, prolog=True, encoding='ascii')
>>> print result.encode('ascii', 'xmlcharrefreplace')
<?xml version="1.0" encoding="ascii"?>
<s... | 9 | 2009-01-30T08:52:10Z | [
"python",
"xml",
"dry"
] |
refactor this dictionary-to-xml converter in python | 494,881 | <p>It's a small thing, really: I have this function that converts dict objects to xml.</p>
<p>Here's the function:</p>
<pre><code>def dictToXml(d):
from xml.sax.saxutils import escape
def unicodify(o):
if o is None:
return u'';
return unicode(o)
lines = []
def addDict(nod... | 3 | 2009-01-30T08:33:12Z | 494,924 | <p>To get rid of repeated "offset+":</p>
<pre><code>offset = 0
def addLine(str):
lines.append(u" " * (offset * 4) + str
</code></pre>
<p>then</p>
<pre><code>...
addLine(u"<%s>" % name)
offset = offset + 1
addDict(value)
offset = offset - 1
addLine(u"</%s>" % name)
</code></pre>
<... | 1 | 2009-01-30T09:13:22Z | [
"python",
"xml",
"dry"
] |
refactor this dictionary-to-xml converter in python | 494,881 | <p>It's a small thing, really: I have this function that converts dict objects to xml.</p>
<p>Here's the function:</p>
<pre><code>def dictToXml(d):
from xml.sax.saxutils import escape
def unicodify(o):
if o is None:
return u'';
return unicode(o)
lines = []
def addDict(nod... | 3 | 2009-01-30T08:33:12Z | 495,295 | <p>Here's what I find helpful when working with XML. Actually create the XML node structure first, then render this into text second.</p>
<p>This separates two unrelated concerns.</p>
<ol>
<li><p>How do I transform my Python structure into an XML object model?</p></li>
<li><p>How to I format that XML object model?</... | 0 | 2009-01-30T12:02:40Z | [
"python",
"xml",
"dry"
] |
refactor this dictionary-to-xml converter in python | 494,881 | <p>It's a small thing, really: I have this function that converts dict objects to xml.</p>
<p>Here's the function:</p>
<pre><code>def dictToXml(d):
from xml.sax.saxutils import escape
def unicodify(o):
if o is None:
return u'';
return unicode(o)
lines = []
def addDict(nod... | 3 | 2009-01-30T08:33:12Z | 495,512 | <p>Your original code produce malformed XML and can produce the same XML for two different dictionaries (is not <em>injective</em>, speaking mathematically).</p>
<p>For example, if you have a list as a value of the only key in a dictionary:</p>
<pre><code> d = { 'list': [1,2,3] }
</code></pre>
<p>I expect that your ... | 1 | 2009-01-30T13:40:01Z | [
"python",
"xml",
"dry"
] |
File and space in Python | 494,919 | <p>I have a file like:</p>
<pre><code><space>
<space>
line1
<space>
column 1 column 2 column 3 ...
.
.
.
<space>
<space>
</code></pre>
<p>How to remove this extra spaces?</p>
<p>I need to extract the heading which will be on <code>line1</code>. Also, I need to extract <code>c... | -2 | 2009-01-30T09:10:03Z | 494,935 | <p>Start by opening the file and reading all the lines:</p>
<pre><code>f = open('filename string');
lines = f.readlines()
</code></pre>
<p>Then...</p>
<pre><code># remove empty lines
lines = [l for l in lines if len(l.strip()) > 0]
header = lines[0]
line = lines[1].split(' ')
column1 = line[0]
column2 = line[1]
.... | 4 | 2009-01-30T09:18:37Z | [
"python",
"file",
"parsing",
"spaces"
] |
File and space in Python | 494,919 | <p>I have a file like:</p>
<pre><code><space>
<space>
line1
<space>
column 1 column 2 column 3 ...
.
.
.
<space>
<space>
</code></pre>
<p>How to remove this extra spaces?</p>
<p>I need to extract the heading which will be on <code>line1</code>. Also, I need to extract <code>c... | -2 | 2009-01-30T09:10:03Z | 494,977 | <p>A straightforward solution, using <a href="http://docs.python.org/library/stdtypes.html#str.strip" rel="nofollow"><code>strip()</code></a> to drop spaces and <a href="http://docs.python.org/library/stdtypes.html#str.split" rel="nofollow"><code>split()</code></a> to separate column data:</p>
<pre><code>>>> ... | 1 | 2009-01-30T09:43:12Z | [
"python",
"file",
"parsing",
"spaces"
] |
File and space in Python | 494,919 | <p>I have a file like:</p>
<pre><code><space>
<space>
line1
<space>
column 1 column 2 column 3 ...
.
.
.
<space>
<space>
</code></pre>
<p>How to remove this extra spaces?</p>
<p>I need to extract the heading which will be on <code>line1</code>. Also, I need to extract <code>c... | -2 | 2009-01-30T09:10:03Z | 495,193 | <p>Using Generator functions to handle each element of parsing</p>
<pre><code>def nonEmptyLines( aFile ):
"""Discard empty lines, yield only non-empty lines."""
for line in aFile:
if len(line) > 0:
yield line
def splitFields( aFile ):
"""Split a non-empty line into fields."""
fo... | 0 | 2009-01-30T11:17:36Z | [
"python",
"file",
"parsing",
"spaces"
] |
HOWTO: XML-RPC dynamic function registration in python? | 494,997 | <p>I am new to XML-RPC.</p>
<pre><code>#client code
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
x,y = arg1,arg2
print proxy.fun1(x,y)
print proxy.fun2(x,y)
</code></pre>
<p>What server should do:</p>
<ol>
<li>load fun1</li>
<li>register fun1</li>
<li>return result</li>
<li>unload fun1</l... | 1 | 2009-01-30T09:54:23Z | 495,027 | <p>Generally the server keeps on running - so register both methods at the start. I don't understand why you want to unregister your functions. Servers stay up and handle multiple requests. You might possible want a <code>shutdown()</code> function that shuts the entire server down, but I don't see anyway to unregister... | 2 | 2009-01-30T10:13:08Z | [
"python",
"xml-rpc"
] |
HOWTO: XML-RPC dynamic function registration in python? | 494,997 | <p>I am new to XML-RPC.</p>
<pre><code>#client code
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
x,y = arg1,arg2
print proxy.fun1(x,y)
print proxy.fun2(x,y)
</code></pre>
<p>What server should do:</p>
<ol>
<li>load fun1</li>
<li>register fun1</li>
<li>return result</li>
<li>unload fun1</l... | 1 | 2009-01-30T09:54:23Z | 499,453 | <p>If you want dynamic registering, register an instance of an object, and then set attributes on that object. You can get more advanced by using the <code>__getattr__</code> method of the class if the function needs to be determined at run time.</p>
<pre><code>class dispatcher(object): pass
def __getattr__(self, ... | 1 | 2009-01-31T20:07:49Z | [
"python",
"xml-rpc"
] |
HOWTO: XML-RPC dynamic function registration in python? | 494,997 | <p>I am new to XML-RPC.</p>
<pre><code>#client code
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
x,y = arg1,arg2
print proxy.fun1(x,y)
print proxy.fun2(x,y)
</code></pre>
<p>What server should do:</p>
<ol>
<li>load fun1</li>
<li>register fun1</li>
<li>return result</li>
<li>unload fun1</l... | 1 | 2009-01-30T09:54:23Z | 25,202,763 | <p>You can register functions dynamically (after the server has been started): </p>
<pre><code>#Server side code:
import sys
from SimpleXMLRPCServer import SimpleXMLRPCServer
def dynRegFunc(): #this function will be registered dynamically, from the client
return True
def registerFunction(function): #this funct... | 1 | 2014-08-08T11:44:29Z | [
"python",
"xml-rpc"
] |
Refactor this Python code to iterate over a container | 495,294 | <p>Surely there is a better way to do this?</p>
<pre><code>results = []
if not queryset is None:
for obj in queryset:
results.append((getattr(obj,field.attname),obj.pk))
</code></pre>
<p>The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I... | 3 | 2009-01-30T12:02:34Z | 495,327 | <p>you can use list comprehensions, but other than that I don't see what you can improve</p>
<pre><code>result = []
if queryset:
result = [(getattr(obj, field.attname), obj.pk) for obj in queryset]
</code></pre>
| 1 | 2009-01-30T12:16:41Z | [
"python",
"django",
"refactoring",
"iterator"
] |
Refactor this Python code to iterate over a container | 495,294 | <p>Surely there is a better way to do this?</p>
<pre><code>results = []
if not queryset is None:
for obj in queryset:
results.append((getattr(obj,field.attname),obj.pk))
</code></pre>
<p>The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I... | 3 | 2009-01-30T12:02:34Z | 495,343 | <pre><code>results = [(getattr(obj, field.attname), obj.pk) for obj in queryset or []]
</code></pre>
| 19 | 2009-01-30T12:22:05Z | [
"python",
"django",
"refactoring",
"iterator"
] |
Refactor this Python code to iterate over a container | 495,294 | <p>Surely there is a better way to do this?</p>
<pre><code>results = []
if not queryset is None:
for obj in queryset:
results.append((getattr(obj,field.attname),obj.pk))
</code></pre>
<p>The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I... | 3 | 2009-01-30T12:02:34Z | 495,400 | <p>How about</p>
<pre><code>for obj in (queryset or []):
# Do your stuff
</code></pre>
<p>It is the same as J.F Sebastians suggestion, only not implemented as a list comprehension.</p>
| 8 | 2009-01-30T12:44:35Z | [
"python",
"django",
"refactoring",
"iterator"
] |
Refactor this Python code to iterate over a container | 495,294 | <p>Surely there is a better way to do this?</p>
<pre><code>results = []
if not queryset is None:
for obj in queryset:
results.append((getattr(obj,field.attname),obj.pk))
</code></pre>
<p>The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I... | 3 | 2009-01-30T12:02:34Z | 522,646 | <p>For what it's worth, Django managers have a "none" queryset that you can use to avoid gratuitous None-checking. Using it to ensure you don't have a null queryset may simplify your code.</p>
<pre><code>if queryset is None:
queryset = MyModel.objects.none()
</code></pre>
<p>References:</p>
<ul>
<li><a href="ht... | 2 | 2009-02-06T23:23:36Z | [
"python",
"django",
"refactoring",
"iterator"
] |
Confusion about global variables in python | 495,422 | <p>I'm new to python, so please excuse what is probably a pretty dumb question. </p>
<p>Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses ... | 11 | 2009-01-30T12:56:57Z | 495,444 | <p>Names beginning with an underscore aren't imported with </p>
<pre><code>from one import *
</code></pre>
| 5 | 2009-01-30T13:07:48Z | [
"python",
"global-variables",
"python-import"
] |
Confusion about global variables in python | 495,422 | <p>I'm new to python, so please excuse what is probably a pretty dumb question. </p>
<p>Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses ... | 11 | 2009-01-30T12:56:57Z | 495,559 | <p>You can also use the <code>__debug__</code> variable for debugging. It is true if the interpreter wasn't started with the -O option. The assert statement might be helpful, too.</p>
| 4 | 2009-01-30T13:57:06Z | [
"python",
"global-variables",
"python-import"
] |
Confusion about global variables in python | 495,422 | <p>I'm new to python, so please excuse what is probably a pretty dumb question. </p>
<p>Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses ... | 11 | 2009-01-30T12:56:57Z | 495,570 | <p>There are more problems than just the leading underscore I'm afraid.</p>
<p>When you call <code>my_function()</code>, it still won't have your <code>debug</code> variable in its namespace, unless you import it from <code>two.py</code>.</p>
<p>Of course, doing that means you'll end up with cyclic dependencies (<cod... | 15 | 2009-01-30T14:01:27Z | [
"python",
"global-variables",
"python-import"
] |
Confusion about global variables in python | 495,422 | <p>I'm new to python, so please excuse what is probably a pretty dumb question. </p>
<p>Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses ... | 11 | 2009-01-30T12:56:57Z | 495,731 | <p>A bit more explanation: The function <code>my_function</code>'s namespace is always in the module <code>one</code>. This means that when the name <code>_debug</code> is not found in <code>my_function</code>, it looks in <code>one</code>, not the namespace from which the function is called. <a href="#495570" rel="nof... | 1 | 2009-01-30T14:45:32Z | [
"python",
"global-variables",
"python-import"
] |
Get rid of '\n' in Python | 495,424 | <p>How to get rid of '\n' at the end of a line ?</p>
| 1 | 2009-01-30T12:58:46Z | 495,428 | <pre><code>"string \n".strip();
</code></pre>
<p>or</p>
<pre><code>"string \n".rstrip();
</code></pre>
| 22 | 2009-01-30T13:00:09Z | [
"python"
] |
Get rid of '\n' in Python | 495,424 | <p>How to get rid of '\n' at the end of a line ?</p>
| 1 | 2009-01-30T12:58:46Z | 495,449 | <p>If, as Rolf suggests in his comment, you want to print text without having a newline automatically appended, use</p>
<pre><code>print "foo",
</code></pre>
<p>Note the trailing comma.</p>
| 18 | 2009-01-30T13:10:51Z | [
"python"
] |
Get rid of '\n' in Python | 495,424 | <p>How to get rid of '\n' at the end of a line ?</p>
| 1 | 2009-01-30T12:58:46Z | 495,654 | <p>If you want a slightly more complex and explicit way of writing output:</p>
<pre><code>import sys
sys.stdout.write("string")
</code></pre>
<p>Then you would responsible for your own newlines.</p>
| 2 | 2009-01-30T14:25:59Z | [
"python"
] |
Get rid of '\n' in Python | 495,424 | <p>How to get rid of '\n' at the end of a line ?</p>
| 1 | 2009-01-30T12:58:46Z | 495,804 | <p>Get rid of just the "\n" at the end of the line:</p>
<pre><code>>>> "string \n".rstrip("\n")
'string '
</code></pre>
<p>Get rid of all whitespace at the end of the line:</p>
<pre><code>>>> "string \n".rstrip()
'string'
</code></pre>
<p>Split text by lines, stripping trailing newlines:</p>
<pre... | 6 | 2009-01-30T15:03:03Z | [
"python"
] |
Get rid of '\n' in Python | 495,424 | <p>How to get rid of '\n' at the end of a line ?</p>
| 1 | 2009-01-30T12:58:46Z | 497,746 | <p>In Python 3, to print a string without a newline, set the end to an empty string:</p>
<pre><code>print("some string", end="")
</code></pre>
| 4 | 2009-01-30T23:59:16Z | [
"python"
] |
Python's version of PHP's time() function | 495,595 | <p>I've looked at the <a href="http://docs.python.org/library/time.html" rel="nofollow">Python Time module</a> and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time().</p>
<p>Am I simply missing something here or is there a common way to do this that's simply not listed th... | 2 | 2009-01-30T14:09:29Z | 495,610 | <pre><code>import time
print int(time.time())
</code></pre>
| 19 | 2009-01-30T14:13:19Z | [
"python",
"time"
] |
Python's version of PHP's time() function | 495,595 | <p>I've looked at the <a href="http://docs.python.org/library/time.html" rel="nofollow">Python Time module</a> and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time().</p>
<p>Am I simply missing something here or is there a common way to do this that's simply not listed th... | 2 | 2009-01-30T14:09:29Z | 495,612 | <p><a href="http://docs.python.org/library/time.html#time.time">time.time()</a> does it, but it might be float instead of int which i assume you expect. that is, precision can be higher than 1 sec on some systems.</p>
| 5 | 2009-01-30T14:14:05Z | [
"python",
"time"
] |
Python's version of PHP's time() function | 495,595 | <p>I've looked at the <a href="http://docs.python.org/library/time.html" rel="nofollow">Python Time module</a> and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time().</p>
<p>Am I simply missing something here or is there a common way to do this that's simply not listed th... | 2 | 2009-01-30T14:09:29Z | 500,445 | <p>I recommend reading <a href="http://seehuhn.de/pages/pdate" rel="nofollow">"Date and Time Representation in Python"</a>. I found it very enlightening.</p>
| 3 | 2009-02-01T08:41:58Z | [
"python",
"time"
] |
Is there any case where len(someObj) does not call someObj's __len__ function? | 496,009 | <p>Is there any case where len(someObj) does not call someObj's <code>__len__</code> function?</p>
<p>I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.<code>__len__</code... | 5 | 2009-01-30T15:58:58Z | 496,019 | <p>According to Mark Pilgrim, it looks like no. <code>len(someObj)</code> is the same as <code>someObj.__len__()</code>;</p>
<p>Cheers!</p>
| -1 | 2009-01-30T16:01:46Z | [
"python"
] |
Is there any case where len(someObj) does not call someObj's __len__ function? | 496,009 | <p>Is there any case where len(someObj) does not call someObj's <code>__len__</code> function?</p>
<p>I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.<code>__len__</code... | 5 | 2009-01-30T15:58:58Z | 496,024 | <p>I think the answer is that it will always work -- according to the Python docs:</p>
<pre><code>__len__(self):
</code></pre>
<p>Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn't define a <code>__nonzero__()</code> method and whose ... | 1 | 2009-01-30T16:03:57Z | [
"python"
] |
Is there any case where len(someObj) does not call someObj's __len__ function? | 496,009 | <p>Is there any case where len(someObj) does not call someObj's <code>__len__</code> function?</p>
<p>I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.<code>__len__</code... | 5 | 2009-01-30T15:58:58Z | 496,038 | <p>What kind of speedup did you see? I cannot imagine it was noticeable was it?</p>
<p>From <a href="http://mail.python.org/pipermail/python-list/2002-May/147079.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2002-May/147079.html</a></p>
<blockquote>
<p>in certain situations there is no
differe... | 7 | 2009-01-30T16:07:33Z | [
"python"
] |
Is there any case where len(someObj) does not call someObj's __len__ function? | 496,009 | <p>Is there any case where len(someObj) does not call someObj's <code>__len__</code> function?</p>
<p>I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.<code>__len__</code... | 5 | 2009-01-30T15:58:58Z | 497,096 | <p>If <code>__len__</code> returns a length over <code>sys.maxsize</code>, <code>len()</code> will raise an exception. This isn't true of calling <code>__len__</code> directly. (In fact you could return any object from <code>__len__</code> which won't be caught unless it goes through <code>len()</code>.)</p>
| 4 | 2009-01-30T20:21:55Z | [
"python"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 496,641 | <p>The easiest is to use an IDE. PyDev is a plugin for eclipse.</p>
<p>I'm not a full on expert in all ways pythonic, but in general I define my class members right under the class definition in python, so if I add members, they're all relative.</p>
<p>My personal opinion is that class members should be declared in o... | 0 | 2009-01-30T18:35:43Z | [
"python",
"variables"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 496,656 | <p>First of all: class attributes, or instance attributes? Or both? =)</p>
<p><em>Usually</em> you just add instance attributes in <code>__init__</code>, and class attributes in the class definition, often before method definitions... which should probably cover 90% of use cases.</p>
<p>If code adds attributes on the... | 7 | 2009-01-30T18:39:58Z | [
"python",
"variables"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 496,701 | <p>It sounds like you're talking about instance variables and not class variables. Note that in the following code a is a class variable and b is an instance variable.</p>
<pre><code>class foo:
a = 0 #class variable
def __init__(self):
self.b = 0 #instance variable
</code></pre>
<p>Regarding the hypothetica... | 3 | 2009-01-30T18:50:16Z | [
"python",
"variables"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 496,820 | <p>Instance variables should be initialized in the class's <code>__init__()</code> method. (In general)</p>
<p>If that's not possible. You can use <code>__dict__</code> to get a dictionary of all instance variables of an object during runtime. If you really need to track this in documentation add a list of instance va... | 4 | 2009-01-30T19:18:27Z | [
"python",
"variables"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 496,906 | <p>A documentation generation system such as <a href="http://epydoc.sourceforge.net/" rel="nofollow">Epydoc</a> can be used as a reference for what instance/class variables an object has, and if you're worried about accidentally creating new variables via typos you can use <a href="http://pychecker.sourceforge.net/" re... | 3 | 2009-01-30T19:36:39Z | [
"python",
"variables"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 496,986 | <p>Consider using <a href="http://docs.python.org/reference/datamodel.html#id3" rel="nofollow"><strong>slots</strong></a>.</p>
<p>For example:</p>
<pre>
class Foo:
__slots__ = "a b c".split()
x = Foo()
x.a =1 # ok
x.b =1 # ok
x.c =1 # ok
x.bb = 1 # will raise "AttributeError: Foo inst... | -2 | 2009-01-30T19:56:27Z | [
"python",
"variables"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 498,284 | <p>I would say, the standard practice to avoid this is to <em>not write classes where you can be 1000 lines away from anything!</em></p>
<p>Seriously, that's way too much for just about any useful class, especially in a language that is as expressive as Python. Using more of what the Standard Library offers and abstra... | 9 | 2009-01-31T04:45:58Z | [
"python",
"variables"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 498,421 | <p>This is a common concern I hear from many programmers who come from a C, C++, or other statically typed language where variables are pre-declared. In fact it was one of the biggest concerns we heard when we were persuading programmers at our organization to abandon C for high-level programs and use Python instead.</... | 2 | 2009-01-31T06:45:25Z | [
"python",
"variables"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 498,435 | <p><a href="http://www.logilab.org/project/pylint" rel="nofollow">pylint</a> can statically detect attributes that aren't detected in <code>__init__</code>, along with many other potential bugs.</p>
<p>I'd also recommend writing unit tests and running your code often to detect these types of "whoopsie" programming mis... | 4 | 2009-01-31T07:15:15Z | [
"python",
"variables"
] |
What's a good way to keep track of class instance variables in Python? | 496,582 | <p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables o... | 8 | 2009-01-30T18:21:13Z | 498,447 | <p>It seems to me that the main issue here is that you're thinking in terms of C++ when you're working in python.</p>
<p>Having a 1000 line class is not a very wise thing anyway in python, (I know it happens alot in C++ though), </p>
<p>Learn to exploit the dynamism that python gives you, for instance you can combine... | 2 | 2009-01-31T07:31:21Z | [
"python",
"variables"
] |
Progress bar not updating during operation | 496,814 | <p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests... | 7 | 2009-01-30T19:17:39Z | 496,995 | <p>More than likely the issue is that in your progress callback, which is where I presume you're updating the progress bar, you're not making a call to manually update the display i.e. run through the GUI's event loop. This is just speculation though, if you can provide more code, it might be easier to narrow it down f... | 1 | 2009-01-30T19:57:36Z | [
"python",
"user-interface",
"gtk",
"progress-bar",
"pygtk"
] |
Progress bar not updating during operation | 496,814 | <p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests... | 7 | 2009-01-30T19:17:39Z | 497,283 | <p>In python 2.x integer operands result in integer division. Try this:</p>
<pre><code>#Callback function invoked when download/upload has progress
def progress(download_t, download_d, upload_t, upload_d):
print 'in fileupload progress'
mainwin.mainw.prog_bar.set_fraction(float(upload_d) / upload_t)
</code></... | 0 | 2009-01-30T21:15:17Z | [
"python",
"user-interface",
"gtk",
"progress-bar",
"pygtk"
] |
Progress bar not updating during operation | 496,814 | <p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests... | 7 | 2009-01-30T19:17:39Z | 497,313 | <p>I'm going to quote the <a href="http://faq.pygtk.org/index.py?req=show&file=faq23.020.htp">PyGTK FAQ</a>:</p>
<blockquote>
<p>You have created a progress bar inside a window, then you start running a loop that does some work:</p>
</blockquote>
<pre><code>while work_left:
...do something...
progressba... | 12 | 2009-01-30T21:26:52Z | [
"python",
"user-interface",
"gtk",
"progress-bar",
"pygtk"
] |
Progress bar not updating during operation | 496,814 | <p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests... | 7 | 2009-01-30T19:17:39Z | 505,876 | <p>Yes, you probably need concurrency, and yes threads are one approach, but if you do use threads, please use an method like this one: <a href="http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html" rel="nofollow">http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html</a> which will abstract a... | 0 | 2009-02-03T02:51:56Z | [
"python",
"user-interface",
"gtk",
"progress-bar",
"pygtk"
] |
Progress bar not updating during operation | 496,814 | <p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests... | 7 | 2009-01-30T19:17:39Z | 661,113 | <p>One option, if you are not married to pycurl, is to use GObject's IO watchers.</p>
<p><a href="http://pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--io-add-watch" rel="nofollow">http://pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--io-add-watch</a></p>
<p>Using this you can ... | 0 | 2009-03-19T05:00:58Z | [
"python",
"user-interface",
"gtk",
"progress-bar",
"pygtk"
] |
Is there a Python equivalent of Perl's x operator? | 497,114 | <p>In Perl, I can replicate strings with the 'x' operator:</p>
<pre><code>$str = "x" x 5;
</code></pre>
<p>Can I do something similar in Python?</p>
| 11 | 2009-01-30T20:27:49Z | 497,119 | <pre><code>>>> "blah" * 5
'blahblahblahblahblah'
</code></pre>
| 31 | 2009-01-30T20:29:15Z | [
"python",
"perl"
] |
Is there a Python equivalent of Perl's x operator? | 497,114 | <p>In Perl, I can replicate strings with the 'x' operator:</p>
<pre><code>$str = "x" x 5;
</code></pre>
<p>Can I do something similar in Python?</p>
| 11 | 2009-01-30T20:27:49Z | 30,409,778 | <p>Here is a reference to the official Python3 docs:</p>
<p><a href="https://docs.python.org/3/library/stdtypes.html#string-methods" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#string-methods</a></p>
<blockquote>
<p>Strings implement all of the <a href="https://docs.python.org/3/library/stdtypes.... | 1 | 2015-05-23T06:43:10Z | [
"python",
"perl"
] |
Python's os.path choking on Hebrew filenames | 497,233 | <p>I'm writing a script that has to move some file around, but unfortunately it doesn't seem <code>os.path</code> plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory:</p>
<p><img src="http://eli.thegreenplace.net/files/tem... | 13 | 2009-01-30T21:03:24Z | 497,309 | <p>It looks like a Unicode vs ASCII issue - <code>os.listdir</code> is returning a list of ASCII strings. </p>
<p>Edit: I tried it on Python 3.0, also on XP SP2, and <code>os.listdir</code> simply omitted the Hebrew filenames instead of listing them at all.</p>
<p>According to the docs, this means it was unable to de... | 3 | 2009-01-30T21:25:24Z | [
"python",
"internationalization",
"hebrew"
] |
Python's os.path choking on Hebrew filenames | 497,233 | <p>I'm writing a script that has to move some file around, but unfortunately it doesn't seem <code>os.path</code> plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory:</p>
<p><img src="http://eli.thegreenplace.net/files/tem... | 13 | 2009-01-30T21:03:24Z | 497,351 | <p>It works like a charm using Python 2.5.1 on OS X:</p>
<pre><code>subdir/bar.txt True
subdir/foo.txt True
subdir/×¢Ö´×ְרִ×ת.txt True
</code></pre>
<p>Maybe that means that this has to do with Windows XP somehow?</p>
<p>EDIT: I also tried with unicode strings to try mimic the Windows behaviour better:</p>
<p... | 0 | 2009-01-30T21:38:37Z | [
"python",
"internationalization",
"hebrew"
] |
Python's os.path choking on Hebrew filenames | 497,233 | <p>I'm writing a script that has to move some file around, but unfortunately it doesn't seem <code>os.path</code> plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory:</p>
<p><img src="http://eli.thegreenplace.net/files/tem... | 13 | 2009-01-30T21:03:24Z | 497,356 | <p>Hmm, after <a href="http://www.amk.ca/python/howto/unicode">some digging</a> it appears that when supplying os.listdir a unicode string, this kinda works:</p>
<pre><code>files = os.listdir(u'test_source')
for f in files:
pf = os.path.join(u'test_source', f)
print pf.encode('ascii', 'replace'), os.path.exi... | 14 | 2009-01-30T21:40:06Z | [
"python",
"internationalization",
"hebrew"
] |
Python's os.path choking on Hebrew filenames | 497,233 | <p>I'm writing a script that has to move some file around, but unfortunately it doesn't seem <code>os.path</code> plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory:</p>
<p><img src="http://eli.thegreenplace.net/files/tem... | 13 | 2009-01-30T21:03:24Z | 497,518 | <p>A question mark is the more or less universal symbol displayed when a unicode character can't be represented in a specific encoding. Your terminal or interactive session under Windows is probably using ASCII or ISO-8859-1 or something. So the actual string is unicode, but it gets translated to ???? when printed to... | 0 | 2009-01-30T22:27:12Z | [
"python",
"internationalization",
"hebrew"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 497,434 | <p>If you're deleting multiple non-adjacent items, then what you describe is the best way (and yes, be sure to start from the highest index).</p>
<p>If your items are adjacent, you can use the slice assignment syntax:</p>
<pre><code>a[2:10] = []
</code></pre>
| 65 | 2009-01-30T22:02:26Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 497,439 | <p>Probably not the best solution for this problem:</p>
<pre><code>indices = 0, 2
somelist = [i for j, i in enumerate(somelist) if j not in indices]
</code></pre>
| 45 | 2009-01-30T22:05:01Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 497,451 | <p>As a function:</p>
<pre><code>def multi_delete(list_, *args):
indexes = sorted(list(args), reverse=True)
for index in indexes:
del list_[index]
return list_
</code></pre>
<p>Runs in <strong>n log(n)</strong> time, which should make it the fastest correct solution yet.</p>
| 13 | 2009-01-30T22:09:38Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 497,455 | <p>You can do that way on a dict, not on a list. In a list elements are in sequence. In a dict they depend only on the index.</p>
<p>Simple code just to explain it <em>by doing</em>:</p>
<pre><code>>>> lst = ['a','b','c']
>>> dct = {0: 'a', 1: 'b', 2:'c'}
>>> lst[0]
'a'
>>> dct[0]
... | 0 | 2009-01-30T22:10:18Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 497,467 | <p>I can actually think of two ways to do it:</p>
<ol>
<li><p>slice the list like (this deletes the 1st,3rd and 8th elements)</p>
<p>somelist = somelist[1:2]+somelist[3:7]+somelist[8:]</p></li>
<li><p>do that in place, but one at a time:</p>
<p>somelist.pop(2)
somelist.pop(0)</p></li>
</ol>
| 0 | 2009-01-30T22:13:28Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 498,074 | <p>So, you essentially want to delete multiple elements in one pass? In that case, the position of the next element to delete will be offset by however many were deleted previously.</p>
<p>Our goal is to delete all the vowels, which are precomputed to be indices 1, 4, and 7. Note that its important the to_delete ind... | 9 | 2009-01-31T02:23:39Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 500,076 | <p>As a specialisation of Greg's answer, you can even use extended slice syntax. eg. If you wanted to delete items 0 and 2:</p>
<pre><code>>>> a= [0, 1, 2, 3, 4]
>>> del a[0:3:2]
>>> a
[1, 3, 4]
</code></pre>
<p>This doesn't cover any arbitrary selection, of course, but it can certainly wor... | 14 | 2009-02-01T02:55:32Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 7,016,104 | <p>here is another method which removes the elements in place. also if your list is really long, it is faster.</p>
<pre><code>>>> a = range(10)
>>> remove = [0,4,5]
>>> from collections import deque
>>> deque((list.pop(a, i) for i in sorted(remove, reverse=True)), maxlen=0)
>>... | 2 | 2011-08-10T18:48:23Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 12,414,409 | <p>I'm a total beginner in Python, and my programming at the moment is crude and dirty to say the least, but my solution was to use a combination of the basic commands I learnt in early tutorials:</p>
<pre><code>SomeList = [1,2,3,4,5,6,7,8,10]
Rem = [0,5,7]
for i in Rem:
SomeList[i]='!' # mark for deletion
for i... | 6 | 2012-09-13T20:36:53Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 20,589,125 | <p>Here is an alternative, that does not use enumerate() to create tuples (as in SilentGhost's original answer).</p>
<p>This seems more readable to me. (Maybe I'd feel differently if I was in the habit of using enumerate.) CAVEAT: I have not tested performance of the two approaches.</p>
<pre><code># Returns a new lis... | 2 | 2013-12-14T22:45:47Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 25,792,322 | <p>Remove method will causes a lot of shift of list elements. I think is better to make a copy:</p>
<pre><code>...
new_list = []
for el in obj.my_list:
if condition_is_true(el):
new_list.append(el)
del obj.my_list
obj.my_list = new_list
...
</code></pre>
| 1 | 2014-09-11T16:12:03Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 26,084,037 | <p>This has been mentioned, but somehow nobody managed to actually get it right.</p>
<p>On <code>O(n)</code> solution would be:</p>
<pre><code>indices = {0, 2}
somelist = [i for j, i in enumerate(somelist) if j not in indices]
</code></pre>
<p>This is really close to <a href="http://stackoverflow.com/a/497439/176335... | 2 | 2014-09-28T10:37:42Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 28,697,246 | <p>For some reason I don't like any of the answers here.
Yes, they work, but strictly speaking most of them aren't deleting elements in a list, are they? (But making a copy and then replacing the original one with the edited copy).</p>
<p>Why not just delete the higher index first?</p>
<p>Is there a reason for this?
... | 30 | 2015-02-24T13:36:44Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 30,901,421 | <p>technically, the answer is NO it is not possible to delete two objects AT THE SAME TIME. However, it IS possible to delete two objects in one line of beautiful python.</p>
<pre><code>del (foo['bar'],foo['baz'])
</code></pre>
<p>will recusrively delete <code>foo['bar']</code>, then <code>foo['baz']</code></p>
| 1 | 2015-06-17T20:08:39Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 32,744,088 | <p>You can use <code>numpy.delete</code> as follows:</p>
<pre><code>import numpy as np
a = ['a', 'l', 3.14, 42, 'u']
I = [0, 2]
np.delete(a, I).tolist()
# Returns: ['l', '42', 'u']
</code></pre>
<p>If you don't mind ending up with a <code>numpy</code> array at the end, you can leave out the <code>.tolist()</code>. Yo... | 4 | 2015-09-23T15:49:17Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 34,121,072 | <p>An alternative list comprehension method that uses list index values:</p>
<pre><code>stuff = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
index = [0, 3, 6]
new = [i for i in stuff if stuff.index(i) not in index]
</code></pre>
<p>This returns:</p>
<pre><code>['b', 'c', 'e', 'f']
</code></pre>
| 1 | 2015-12-06T18:32:34Z | [
"python",
"list"
] |
Deleting multiple elements from a list | 497,426 | <p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements firs... | 78 | 2009-01-30T21:59:38Z | 34,349,945 | <p>we can do this by use of a for loop iterating over the indexes after sorting the index list in descending order</p>
<pre><code>mylist=[66.25, 333, 1, 4, 6, 7, 8, 56, 8769, 65]
indexes = 4,6
indexes = sorted(indexes, reverse=True)
for i in index:
mylist.pop(i)
print mylist
</code></pre>
| 1 | 2015-12-18T06:50:23Z | [
"python",
"list"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.