enumerate

Only index needed: enumerate or (x)range?

Only index needed: enumerate or (x)range? Question: If I want to use only the index within a loop, should I better use the range/xrange function in combination with len() a = [1,2,3] for i in xrange(len(a)): print i or enumerate? Even if I won’t use p at all? for i,p in enumerate(a): print i Asked …

Total answers: 8

(Python) Counting lines in a huge (>10GB) file as fast as possible

(Python) Counting lines in a huge (>10GB) file as fast as possible Question: I have a really simple script right now that counts lines in a text file using enumerate(): i = 0 f = open(“C:/Users/guest/Desktop/file.log”, “r”) for i, line in enumerate(f): pass print i + 1 f.close() This takes around 3 and a half …

Total answers: 5

Is enumerate in python lazy?

Is enumerate in python lazy? Question: I’d like to know what happens when I pass the result of a generator function to python’s enumerate(). Example: def veryBigHello(): i = 0 while i < 10000000: i += 1 yield "hello" numbered = enumerate(veryBigHello()) for i, word in numbered: print i, word Is the enumeration iterated lazily, …

Total answers: 4

Python: Unpacking an inner nested tuple/list while still getting its index number

Python: Unpacking an inner nested tuple/list while still getting its index number Question: I am familiar with using enumerate(): >>> seq_flat = (‘A’, ‘B’, ‘C’) >>> for num, entry in enumerate(seq_flat): print num, entry 0 A 1 B 2 C I want to be able to do the same for a nested list: >>> seq_nested …

Total answers: 1

How do I enumerate() over a list of tuples in Python?

How do I enumerate() over a list of tuples in Python? Question: I’ve got some code like this: letters = [(‘a’, ‘A’), (‘b’, ‘B’)] i = 0 for (lowercase, uppercase) in letters: print “Letter #%d is %s/%s” % (i, lowercase, uppercase) i += 1 I’ve been told that there’s an enumerate() function that can take …

Total answers: 4