Python one line for loop [duplicate] - python

This question already has answers here:
How do you join all items in a list?
(4 answers)
Closed 8 years ago.
I ran into a problem when trying to shorten my script.
First of all this is my script:
letters_list = ['d', '7', '9']
letter_string = ""
for letter in letters_list:
letter_string +=letter
print letter_string
I need to put this whole thing into one line.
How can I do that?

You can simply join the characters with str.join like this
print "".join(letters_list)
# d79
Quoting from the documentation,
CPython implementation detail: If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s = s + t or s += t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.
So str.join is better than letter_string += letter way of joining strings.

letter_string = "".join(letters_list)

Related

How to get output of for-loop? [duplicate]

This question already has answers here:
How do I save results of a "for" loop into a single variable? [duplicate]
(2 answers)
Closed 1 year ago.
I have written a code that prints all letters, but I want to take its output to put it in a variable. i.e. I want to take all letters and save it in one variable instead of writing all letters manually.
for letter in range(97, 123):
letters = chr(letter)
print(letters, end=" ")
If you wish to complete this in one line, Python has a neat way of allowing you to create lists with the use of list comprehensions. If you wish to know more about what a list comprehension is, you may see point 5.1.3 here.
letters = [chr(letter) for letter in range(97, 123)]
A more comprehensible way of solving the problem is to append the characters to a letters list which should be defined before you begin to loop your range.
letters = []
for letter in range(97, 123):
letters.append(chr(letter))
print(letters)
The Python documentation does a good job of explaining the different data structures used throughout the programming language, I hope this clears up the various ways to solve your problem described.

Using line breaks in variable assignment [closed]

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 5 years ago.
Improve this question
I'm working on something in python and I have several variables that are calculated by very long formulas. I've done some searching on this site, and I found that python allows for implicit line breaking, which would be a solution for me as I can stretch the formula over multiple lines:
line-breaking
Now currently I have been working in a different way. Let me give you an example, if A would be given by the following formula:
A = b + c + d + e
I would be coding it as:
A = b + c
A += d + e
I was wondering what would be the preferred method. Is there a computational advantage to use implicit line-breaking over my current method?
We'd need more context to be sure, but here are some example cases.
For strings, as an implementation detail of CPython, the explicit split would be better (sometimes much better), because there is an optimization for an add (a = a + b) or inplace add (a += b) where the add/iadd instruction itself is immediately followed by a store to the left-hand side of the add. That said, for strings, you'll get more reliable performance regardless of operand size or the specific Python interpreter by doing A = ''.join((b, c, d, e)) rather than repeated concatenation.
For ints, floats and complex types, the single line approach is going to be ever so slightly more performant, solely because it avoids an unnecessary store and load instruction, but the difference is trivial; they're all immutable, scalar values, so no in-place manipulation of values occurs regardless, you'll have the same number of temporaries created during processing, the only question is whether they get (briefly) bound to a local name or not.
Frankly, if it's not a matter of concatenating strings or sequences (the former should be done with ''.join, the latter with itertools.chain to get O(n) performance), the preferred approach is not line continuation characters (which can easily get messed up by invisible trailing white space) but simple parentheses for grouping. If the real names of A = b + c + d + e were too long to fit on a line, my preferred approach would be:
A = (b + c +
d + e)
PEP8 prefers to break lines before the next operator, not after, so strictly PEP8 code would be:
A = (b + c
+ d + e)
This is the approach supported by PEP8 (the Python style guide), which says:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
The only real case for using backslashes instead is when parentheses aren't a legal part of the grammar (the link includes an example for with statements).

Why is concatenating strings with ''.join(list) so popular? [duplicate]

This question already has answers here:
Python string join performance
(7 answers)
Closed 5 years ago.
I know that ''.join(list) is the preferred method to concatenate strings as opposed to say:
for x in list:
s += x
My question is why is this much faster?
Also, what if I need to concatenate items that are not already in a list? Is it still faster to put them in a list just for the purpose of doing the ''.join(list)?
EDIT: This is different than the previously linked question because I'm specifically interested in knowing if the items are not in a list already, is it still recommended for performance reasons to put them in a list for the sole purpose of joining.
This is faster because the join method gets to dive "under the surface" and use lower-level optimizations not available from the Python layer. The loop has to plod through the sequence generator and deal with each object in turn. Also, your loop has to build a new string on each iteration, a slow process. join gets to use mutable strings on the C layer or below.
If the objects aren't already in a list ... it depends on the application. However, I suspect that almost any such application will have to go through that loop-ish overhead somewhere just to form the list, so you'd lose some of the advantage of join, although the mutable string would still save time.
Yes, join is faster because it doesn't need to keep building new strings.
But you don't need a list to use join! You can give it any iterable, such as a generator expression:
''.join(x for x in lst if x != 'toss')
It appears that join is optimized when you use a list though. All of these are equivalent, but the one with a list comprehension is fastest.
>>> timeit("s=''.join('x' for i in range(200) if i!=47)")
15.870241802178043
>>> timeit("s=''.join(['x' for i in range(200) if i!=47])")
11.294011708363996
>>> timeit("s=''\nfor i in range(200):\n if i!=47:\n s+='x'")
16.86279364279278

Joining Lists and Splitting Strings [duplicate]

This question already has answers here:
Why is it string.join(list) instead of list.join(string)?
(11 answers)
Closed 7 years ago.
I have some previous experience with C++ and just getting started up with Python. I read this text from Dive into Python :
In my experience, a general idea is, if you want to perform an operation on object 'O', you call a method on that object to do it.
Eg. If I have a list object, and I want to get summation of all elements, I would do something like :
listObject.getSumOfAllElements()
However, the call given in above book excerpt looks a little odd to me. To me this would make more sense :
return (["%s=%s" % (k, v) for k, v in params.items()]).join(";")
i.e. join all the elements of the list as a string, and here, use this parameter ';' as a delimiter.
Is this a design difference or just syntactically a little different than what I am thinking ?
Edit:
For completion, the book says this a little later :
Is this a design difference or just syntactically a little different than what I am thinking?
Yes, I think it is by design. The join function is intentionally generic, so that it can be used with any iterable (including iterator objects and generators). This avoids implementing join for list, tuple, set etc separately.

Length of the longest sublist? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python’s most efficient way to choose longest string in list?
I have a list L
L = [[1,2,3],[5,7],[1,3],[77]]
I want to return the length of the longest sublist without needing to loop through them, in this case 3 because [1,2,3] is length 3 and it is the longest of the four sublists. I tried len(max(L)) but this doesn't do what I want. Any way to do this or is a loop my only way?
max(L,key=len) will give you the object with the longest length ([1,2,3] in your example) -- To actually get the length (if that's all you care about), you can do len(max(L,key=len)) which is a bit ugly -- I'd break it up onto 2 lines. Or you can use the version supplied by ecatamur.
All of these answers have loops -- in my case, the loops are implicit which usually means they'll be executed in optimized native machine code. If you think about it, How could you know which element is the longest without looking at each one?
Finally, note that key=function isn't a feature that is specific to max. A lot of the python builtins (max,min,sorted,itertools.groupby,...) use this particular keyword argument. It's definitely worth investing a little time to understand how it works and what it typically does.
Try a comprehension:
max(len(l) for l in L)

Categories

Resources