Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Why is the position of a loop header relative to the body is different from its usual one? How come a loop variable appears before the loop?
The code is taken from various programs
n=reduce(operator.mul,[int(x) for x in str(n)],1)
return value == sum(int(x) ** len(str(value)) for x in str(value))
It is, technically, not a loop. This is so-called comprehension syntax, borrowed into Python from Haskell (see comments for the full lineage). To follow traditions of math notation for sets, and distinguish a comprehension from a usual loop, loop-like enumerator comes in the end of the notation.
Find more of history of various comprehensions and generator expression in Python here http://python-history.blogspot.com/2010/06/from-list-comprehensions-to-generator.html
NOTE. The first of your expression contains a list comprehension, the list comprehension is the first and the most popular pythonic comprehension. The second one contains a generator expression, which, though, originally were called generator comprehension, according to PEP 289.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Recently, I have learned a bit about the filter method, an alternative to using list comprehensions.
Say I have a list as such:
names = ["Bob", "Billy", "Samuel", "Adam", "Rob"]
Now, I would like to get a list containing the names that start with the letter, "B". I could go about this in a couple of ways. This is one:
b_starting_names = list(filter(lambda name: name.startswith("B"), names))
This is another:
b_starting_names = [name for name in names if name.startswith("B")]
Could someone please explain what the difference is between a list comprehension and the filter function, and why someone may want to use one over the other?
There's no harm in using either. A similar comment can be made about map.
I tend to use whatever one feels easier to read. In your case I would avoid using the lambda as it is a bit verbose, and instead use the comprehension.
I would use filter or map methods if I already had a function existing I could just pass to the method, which would be more terse than the comprehension.
For example, say I write a program for finding the length of the largest name:
# Using map
longest = max(map(len, names))
# Using generator expression
longest = max(len(name) for name in names))
In the above example I would choose map over the generator expression, but it's entirely personal preference.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Could you please tell me why it is considered as "not pythonic" when I need the index and the value when looping over a list and use:
a = [1,2,3]
for i in range(len(a)):
# i is the idx
# a[i] is the value
but rather it is recommended to use
for idx, val in enumerate(a):
print idx, val
who defines "pythonic" and why is the latter one better? I mean it's not that much better concerning readability, is it!?
Thanks in advance
First of all, the first way is ugly: You either need a separate variable assignment to get the element or use a[i] all the time which could theoretically be an expensive operation. Imagine a being a database cursor: When you iterate it (a.__iter__ being called) the object can safely assume that you are going to iterate over all its items. So all or at least multiple rows could be retrieved at once. When getting the length such an optimization would be stupid though since you surely don't want to retrieve data just because you want the number of items. Also, when retrieving a specific item you cannot assume that other items will be retrieved, too.
Additionally, using enumerate() works with any iterable while range(len()) only works with countable, indexable objects.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Could you please tell me why it is considered as "not pythonic" when I need the index and the value when looping over a list and use:
a = [1,2,3]
for i in range(len(a)):
# i is the idx
# a[i] is the value
but rather it is recommended to use
for idx, val in enumerate(a):
print idx, val
who defines "pythonic" and why is the latter one better? I mean it's not that much better concerning readability, is it!?
Thanks in advance
First of all, the first way is ugly: You either need a separate variable assignment to get the element or use a[i] all the time which could theoretically be an expensive operation. Imagine a being a database cursor: When you iterate it (a.__iter__ being called) the object can safely assume that you are going to iterate over all its items. So all or at least multiple rows could be retrieved at once. When getting the length such an optimization would be stupid though since you surely don't want to retrieve data just because you want the number of items. Also, when retrieving a specific item you cannot assume that other items will be retrieved, too.
Additionally, using enumerate() works with any iterable while range(len()) only works with countable, indexable objects.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Now I'm talking about MATH brackets, not python brackets, I know that parentheses () work like in maths, ex:
i = 5*(2+2)
print (i)
#output = 20
But square brackets [] and curly brackets {} don't work... (I know why they don't work)
Thank you,
Using Python 3.2.2
You don't need "math" brackets -- just use nested parentheses. Humans use [] in writing out complex math expressions to make them more readable to other humans, but this isn't necessary. They don't mean anything different than regular parentheses. So, when writing code, just stick to the parentheses.
They don't work as grouping constructs - only parentheses will do that.
Square brackets define a list.
Curly brackets define either a set or a dictionary (if the elements appear as key: value).
Further to this, the extra level of clarity when dealing with multiple nestings is unnecessary, as most good IDEs will let you know when the parentheses count is imbalanced (and, you will also notice when the count is imbalanced from repetition).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to figure out how to compare a string to the 0th element in the list (technically the bottom). The list is also a class instance and looks like this:
#define class called GEL
class GEL:
def __init__(self,eventtime,type):
self.eventtime=eventtime
self.type=type
myList=[]
And when I add something to the list:
myList.append(GEL(time,type)) ##Type can be either 'Arrival' or 'Departure'
For which the list will be (1.343432,'Arrival')
So I want to compare 'Arrival' with the type item in the list.
for i in range(5): ##loop for insertions and deletions
Type=[a.type for a in myList] ##Actually goes to the last type, but want first
if 'Arrival' in Type:
##DO STUFF
else:
##HELLO WORLD
#sortlist
myList.pop(0)
What would be the correct way just get the first type in the list?
Sorry for the poor jargon, am still learning Python.
EDIT: I think I may have solved. It gets me what I want. If anyone could tell me if this would be ok:
if 'Arrival' in Type[0]:
I think you just need this
if mylist[0].type == 'Arrival':