We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
lines is a list of strings from the input text, one for each line.
zip is used to get esch line along with an incrementing integer, which are put into a LineLocation object.
The square brackets are a "list comprehension", which means that any code inside the brackets operates on the provided list (the result of zip() here) and is then put into another list. here the outpu list is locations, which is a list of LineLocation objects.
Next I use another list conprehension to convert the list of locations into a list of strings called chars, each string is one character long and comes from taking the nth character of the line.
finally, join() is used in the chars list to convert it into a string.
I hope that clarifies things, ask again if not!
While my code is a silly example, I hope it has given you some ideas of the power of list comprehensions - they can really make your code more concise in real problems. An alternative to them is using map, which is analogous to the same function in other languages (e.g. javascript, scala) or select in C#.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Say "Hello, World!" With Python
You are viewing a single comment's thread. Return to all comments →
lines is a list of strings from the input text, one for each line. zip is used to get esch line along with an incrementing integer, which are put into a LineLocation object. The square brackets are a "list comprehension", which means that any code inside the brackets operates on the provided list (the result of zip() here) and is then put into another list. here the outpu list is locations, which is a list of LineLocation objects. Next I use another list conprehension to convert the list of locations into a list of strings called chars, each string is one character long and comes from taking the nth character of the line. finally, join() is used in the chars list to convert it into a string.
I hope that clarifies things, ask again if not!
While my code is a silly example, I hope it has given you some ideas of the power of list comprehensions - they can really make your code more concise in real problems. An alternative to them is using map, which is analogous to the same function in other languages (e.g. javascript, scala) or select in C#.