The range() function is a built-in function in Python that generates a sequence of numbers. It is often used to create a loop that runs a specific number of times. Here are some tips for using range() to write efficient code:
- Use
range()withforloops: Instead of creating a list of numbers usingrange()and then iterating over the list with aforloop, userange()directly in theforloop. This avoids the overhead of creating a list and saves memory.
Example:
# Inefficient codemy_list = [1, 2, 3, 4, 5]for i in my_list: print(i)# Efficient codefor i in range(1, 6): print(i) |
- Use
range()with list comprehensions: List comprehensions can be used to create a list of numbers usingrange()in a concise way.
Example:
# Inefficient codemy_list = []for i in range(1, 6): my_list.append(i)# Efficient codemy_list = [i for i in range(1, 6)] |
- Use
range()withzip():zip()is a built-in function in Python that takes two or more iterables and returns an iterator that aggregates them. When used withrange(), it can be used to loop over two or more sequences simultaneously.
Example:
# Inefficient codelist1 = [1, 2, 3]list2 = [4, 5, 6]for i in range(len(list1)): print(list1[i], list2[i])# Efficient codelist1 = [1, 2, 3]list2 = [4, 5, 6]for x, y in zip(list1, list2): print(x, y) |
By using range() efficiently in your code, you can improve performance and reduce memory usage.