How to read a file line-by-line into a list?

This code will read the entire file into memory and remove all whitespace characters (newlines and spaces) from the end of each line: with open(filename) as file: lines = file.readlines() lines = [line.rstrip() for line in lines] If you’re working with a large file, then you should instead read and process it line-by-line: with open(filename) … Read more

Why is reading lines from stdin much slower in C++ than Python?

tl;dr: Because of different default settings in C++ requiring more system calls. By default, cin is synchronized with stdio, which causes it to avoid any input buffering. If you add this to the top of your main, you should see much better performance: std::ios_base::sync_with_stdio(false); Normally, when an input stream is buffered, instead of reading one … Read more

How do I print curly-brace characters in a string while using .format?

You need to double the {{ and }}: >>> x = ” {{ Hello }} {0} ” >>> print(x.format(42)) ‘ { Hello } 42 ‘ Here’s the relevant part of the Python documentation for format string syntax: Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is … Read more

How can I randomly select an item from a list?

Use random.choice(): import random foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] print(random.choice(foo)) For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice(): import secrets foo = [‘battery’, ‘correct’, ‘horse’, ‘staple’] print(secrets.choice(foo)) secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class: import random … Read more