Tell me please, how does it work exactly? Why does each iteration result write to array?
list_of_strings = [a.rstrip('\n') for a in list_of_strings]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This takes a list of strings (stored in variable
list_of_strings), iterates through it assigning each string temporarily to variableaeach time through and strips the\ncharacter from each string. The result is a list of strings that is assigned back to the same variable.This is using List Comprehension. Generally most for-loops and list operations involving append() can be converted to equivalent list comprehensions. Here’s a simple example demonstrating this:
could be rewritten simply as
You may find it instructive to take your list comprehension and rewrite it with a
for-loop to test your understanding (both should produce identical results).In most cases, list comprehension is faster than the equivalent
for-loop and clearly a more compact way to express an algorithm. You can have nested list comprehensions too (just as you can have nestedfor-loops), but they can quickly become hard to comprehend 🙂Also, while not shown in the code above, you can filter values in the list comprehension, i.e., including them (or not) in the resulting list depending on whether they meet some criteria.
As an aside, Python also provides similar set comprehensions and generator expressions. It’s well worth learning about all of these.