I'd like the convienience of
for i, line in enumerate(open(sys.argv[1])): print i, line
when doing the following in Scala
for (line <- Source.fromFile(args(0)).getLines()) { println(line) }
Enumerate() in PythonEnumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method.
By definition, an enumeration is a set of members that have associated unique constant values. Enumeration is often called enum. Python provides you with the enum module that contains the Enum type for defining new enumerations. And you define a new enumeration type by subclassing the Enum class.
Using enumerate() is more beautiful but not faster for looping over a collection and indices. Mind your Python version when looping over two collections - use itertools for Python 2.
enumerate() allows us to iterate through a sequence but it keeps track of both the index and the element. enumerate(iterable, start=0) The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary.
You can use the zipWithIndex
from Iterable trait:
for ((line, i) <- Source.fromFile(args(0)).getLines().zipWithIndex) { println(i, line) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With