I'd like to remove the brackets around my querysets using list comprehension.  This is what I have :   foo = [[&lt;queryset: two&gt;], [&lt;queryset: four&gt;], [&lt;queryset: one&gt;]]    And this is what I want :   bar = [&lt;queryset: two&gt;, &lt;queryset: four&gt;, &lt;queryset: one&gt;]    I tried to use list comprehension like so but it didn't change anything :  bar = [x for x in foo]   What am I doing wrong ?
1083
Is there a simple way to flatten a list of iterables with a list comprehension, or failing that, what would you all consider to be the best way to flatten a shallow list like this, balancing performance and readability?  I tried to flatten such a list with a nested list comprehension, like this:  [image for image in menuitem for menuitem in list_of_menuitems]   But I get in trouble of the NameError variety there, because the name 'menuitem' is not defined.  After googling and looking around on Stack Overflow, I got the desired results with a reduce statement:  reduce(list.__add__, map(lambda x: list(x), list_of_menuitems))   But this method is fairly unreadable because I need that list(x) call there because x is a Django QuerySet object.  Conclusion:   Thanks to everyone who contributed to this question.  Here is a summary of what I learned.  I'm also making this a community wiki in case others want to add to or correct these observations.  My original reduce statement is redundant and is better written this way:  &gt;&gt;&gt; reduce(list.__add__, (list(mi) for mi in list_of_menuitems))   This is the correct syntax for a nested list comprehension (Brilliant summary !):  &gt;&gt;&gt; [image for mi in list_of_menuitems for image in mi]   But neither of these methods are as efficient as using itertools.chain:  &gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; list(chain(*list_of_menuitems))   And as @cdleary notes, it's probably better style to avoid * operator magic by using chain.from_iterable like so:  &gt;&gt;&gt; chain = itertools.chain.from_iterable([[1,2],[3],[5,89],[],[6]]) &gt;&gt;&gt; print(list(chain)) &gt;&gt;&gt; [1, 2, 3, 5, 89, 6]
103588
In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:  "[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"   Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:  print 'my list is %s'%(list)   it looks something like this:  [&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;]   how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?
124140
I'm getting some really weird results from my QUERY() Here is an image with an example:    I'm querying for the name where No Show = "No Show". It find the correct name Name 5 but also returns a concatenated list of names separated by a space.   Why is this happening? How do I fix it?
49176
Why does python 2.5.2 have the following behavior  &gt;&gt;&gt;[2].extend([]) == [2] False  &gt;&gt;&gt; [2].extend([]) == None True  $ python --version Python 2.5.2   I assume I'm not understanding something here, but intuitively I'd think that [2].extend([]) should yield [2]
49084
How do I remove an element from a list by index in Python?  I found the list.remove method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.
109666
What is the best way to copy a list? I know the following ways, which one is better? Or is there another way?  lst = ['one', 2, 3]  lst1 = list(lst)  lst2 = lst[:]  import copy lst3 = copy.copy(lst)
107965
I am working on a problem with the following set:  $$S =  \{\varnothing,\{\varnothing\}\}$$  My solution was: $P(S) = \{\varnothing, \{\varnothing\},\{ \varnothing , \{ \varnothing \}\}\}$, but the solution on the textbook shows: $P(S) = \{ \varnothing , \{ \varnothing \}, \{\{\varnothing\}\}, \{ \varnothing , \{ \varnothing \}\}$  Where does the $\{\{\varnothing\}\}$ come from?  Thanks
107288
In Django model QuerySets, I see that there is a __gt and __lt for comparative values, but is there a __ne or != (not equals)? I want to filter out using a not equals. For example, for Model:     bool a;     int x;  I want to do results = Model.objects.exclude(a=True, x!=5)  The != is not correct syntax. I also tried __ne. I ended up using: results = Model.objects.exclude(a=True, x__lt=5).exclude(a=True, x__gt=5)
410
I needed to create a list of lists in Python, so I typed the following: my_list = [[1] * 4] * 3  The list looked like this: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]    Then I changed one of the innermost values: my_list[0][0] = 5  Now my list looks like this: [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]    which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?
30489
I have a Python regular expression that contains a group which can occur zero or many times - but when I retrieve the list of groups afterwards, only the last one is present. Example:  re.search("(\w)*", "abcdefg").groups()  this returns the list ('g',)  I need it to return ('a','b','c','d','e','f','g',)  Is that possible? How can I do it?
3507
I accidentally discovered () that a closing square bracket within an optional argument delimited by [ ] can cause problems.  Here is example code illustrating the issue:  \documentclass{article}   \begin{document}  \tableofcontents  \section[Square brackets ([ and ])]{Square brackets: [ and ]} % bad: the TOC now has "Square brackets ([ and", and the actual title is a mere ")".  Some text.  \section[{Square brackets ([ and ])}]{Square brackets: [ and ]} % good (works as originally intended)  Some text.  \end{document}   The text to be used as the optional (as well as the non-optional) argument contains a ], and this character is not supposed to function as the optional argument terminator but as a matching square bracket/parenthesis. Perhaps this is as it should be, but the question is how to best circumvent any potential problems. Enclosing this in a group works, but I don't know whether doing this has other side effects (perhaps not here in the case of \section but hopefully someone else has a better example of where grouping could lead to a problem). There is no (obvious) way other than writing [{ }] because [ and ] are not normally escaped. That [ and ] are normal characters and bear syntactic function (as optional argument delimiters) creates this potentially problematic situation.  Is simply enclosing the entire optional argument in a group ({ }) a good solution? Are there other/better ways?
53456
What is the difference between:  some_list1 = [] some_list1.append("something")   and  some_list2 = [] some_list2 += ["something"]
17166
I have a list of integers, List&lt;Integer&gt; and I'd like to convert all the integer objects into Strings, thus finishing up with a new List&lt;String&gt;.  Naturally, I could create a new List&lt;String&gt; and loop through the list calling String.valueOf() for each integer, but I was wondering if there was a better (read: more automatic) way of doing it?
95092
Why does list.index throw an exception, instead of using an arbitrary value (for example, -1)? What's the idea behind this?  To me it looks cleaner to deal with special values, rather than exceptions.  EDIT: I didn't realize -1 is a potentially valid value. Nevertheless, why not something else? How about a value of None?
49733
I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the HttpRequest object? My HttpRequest.GET currently returns an empty QueryDict object. I'd like to learn how to do this without a library, so I can get to know Django better.
1360
I want to create a list of lambda objects from a list of constants in Python; for instance:  listOfNumbers = [1,2,3,4,5] square = lambda x: x * x listOfLambdas = [lambda: square(i) for i in listOfNumbers]   This will create a list of lambda objects, however, when I run them:  for f in listOfLambdas:     print f(),   I would expect that it would print  1 4 9 16 25   Instead, it prints:  25 25 25 25 25   It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.  EDIT: a bit more of trying things and such came up with this:  listOfLambdas = [] for num in listOfNumbers:     action = lambda: square(num)     listOfLambdas.append(action)     print action()   Prints the expected squares from 1 to 25, but then using the earlier print statement:  for f in listOfLambdas:     print f(),   still gives me all 25s. How did the existing lambda objects change between those two print calls?  Related question:
1603
We used to be able to , but that now appears to be broken.  I'd expect a  to return a result, but instead the search engine appears to put quotes around the whole request; the search box shows the search has been replaced with "[python] += list" and the  I was looking for doesn't appear among the returned questions.  Using quotes around the symbols do not seem to help here;  returns an empty result.