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.
Related
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 1 year ago.
Improve this question
prepping for interviews and this is something i couldnt find. https://blog.finxter.com/python-list-reverse/#:~:text=The%20time%20complexity%20of%20the,the%20number%20of%20list%20elements. says .reverse() is the O(n) which I assume is because it replaces every index. is [::-1] just printing the list backwards or is something similar going on
list.reverse operates in place. That means that it almost certainly does something like this under the hood:
for i in range(len(self) // 2):
j = len(self) - 1 - i
self[i], self[j] = self[j], self[i]
The actual method is implemented in C, so of course it will be much more verbose, especially in the swapping operation.
list[::-1] creates a copy of the original. The idea is similar, but since the reversal of not in place, you have the luxury of just writing to a destination index rather than swapping via a temporary object:
new = [None] * len(self)
for i in range(len(self)):
j = len(self) - 1 - i
new[j] = self[i]
The actual slice processing code is much more complex since it has to be able to accept integers and all sorts of unorthodox slice expressions that set custom start and stop bounds, and step sizes.
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 needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
for x in s[:].split():
s = s.replace(x, x.capitalize())
I want to know how the for loop will progress and what exactly s[:] means and will do?
Assuming s is a string, s[:] makes a copy of the string, and split() splits the string at spaces and returns an array of substrings, the for loop will then iterate over the substrings.
It's actually unnecessary because split returns an array, so even the though the for loop modifies the original string, the loop iterable isn't reevaluated multiple times, so you don't need to copy it.
s is very likely to be a string because the split is a method in str (of course, you can also say that s is an instance, which comes from a class that is defined by the user in which also has a split method ...)
Normally s[:] is like a slice. The following can help you to understand.
s ='abc AB C dd'
print(s)
print(s[:]) # same as s
print(s[:3]) # abc
print(s[4:6]) # AB
print(s[-1]) # d
for x in s[:].split():
s = s.replace(x, x.capitalize())
print(s) # Abc Ab C Dd # Now you know the capitalize is what, right?
digression
The following is a digression.
I think your question is very bad,
First, this question is very basic.
second, its subject is not good.
Note that an ideal Stack Overflow question is specific and narrow -- the idea is to be a huge FAQ.
And now, you tell me searching how the loop will work? I mean, if you are a programmer who must know how the loop it is.
so when you ask a question, you have to think twice about what the title name can benefit everyone. (not just you only)
I suggest that you can delete this question after you understand it.
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 7 years ago.
Improve this question
I am making an attempt to learn recursion better so I have been practicing some problems.
A common problem is flatten an list of lists to a single list. For example
[3,4,[1,2]] so the desired result will be [3,4,1,2].
The way I am approaching the problem is:
is 0 element a list - no
is 1 element a list - no
is 2 element a
list - yes
call the function again and do tests again
My base case will be to return if element is not a list.
Is there a better approach to understand recursion better?
Your approach is in the right direction, but you should not check more than the first element. In general - a "pure" recursive solution will only have to look at the "head" of the list (first element), and the "tail" (list[1:]).
something like (python like pseudo code):
def flatten(l):
if len(l) == 0:
return []
if isinstance(l[0], list):
left = flatten(l[0])
else:
left = [l[0]]
return left + flatten(l[1:])
You example is certainly one that works however it may be slightly too simple for you to get a full understanding. I found that maze problems were the most helpful in me understanding recursive problems. The main preface is there is a 2x2 array consisting of two different values. One value denotes a wall within the maze and the other value denotes empty space. Your job would be to traverse through the maze using recursion. Here is an example problem and solution:
https://www.cs.bu.edu/teaching/alg/maze/
Hope this helps!!
You should.
Create a new list (passed) before calling function. Call function.
Loop through the old one and check if the type of list if so, then call function recursive.
else add element to passed list.
aList = [3,4,[1,2]]
def flatten(inList,outList):
for elem in inList:
if isinstance(elem,list):
flatten(elem,outList)
else:
outList.append(elem)
bList = list()
flatten(aList,bList)
print bList