Originally posted on makeuseof.
Looping through a list is an incredibly common task, so make sure you’re doing it in the best way possible.
Python is one of the fastest-growing programming languages. Developers use it for machine learning and data science, among other types of application. Before you start learning more advanced aspects of the language, you should master one of the most common data structures: lists.
Lists in Python are arrays, familiar from other programming languages like C and C++. You can change the size of a list, and Python builds in various list methods for convenience. You can store multiple data types within a list, such as strings, objects, and even other lists.
Why Use Different Looping Techniques?
You may be wondering whether it’s worth learning different ways to traverse a Python list when a straightforward for loop can do the job.
Often it’s easier to use a shorthand method, such as a list comprehension or lambda function, to keep your code concise and less cluttered. It also helps in deciding what traversal technique would be most effective for a complex list with many elements.
More importantly, it’s common for interviewers to ask complex list traversal questions. If you know the different ways to traverse lists, you will be better prepared to answer those tough questions.
1. Traversing Using For Loop and Range Method
One of the most common methods to traverse a Python list is to use a for loop, and they are very similar to other programming languages.
arr = [10, 20, 30, 40]
for val in arr:
print('value', val)
Alternatively, you can also use the range() method to have more control over your for loop. The range() method takes three arguments:
- start: Denotes the starting index of the for loop traversal.
- stop: Tells the program the final/stopping index for the for loop traversal. It’s common to use the list’s length (number of elements) as the stopping index.
- step: The step size argument is optional. If provided, it sets the amount that the for loop increases its running counter by each time. By default, the step size is 1.
To traverse a Python list using range():
arr = [10, 20, 30, 40, 50, 60]
for key in range(0, len(arr), 2):
print('num', key)
The above example runs the for loop from index 0 until the length of the array and increments the loop counter by 2.
2. Shorthand Traversing Using List Comprehension
One of Python’s most intuitive features is list comprehension. It lets you write simple one-line solutions to a variety of different problems.
For example, to calculate the square of the first 10 numbers, you can simply use:
sq = [x ** 2 for x in range(10)]
Given a list of numbers, you can print them using list comprehension as follows:
arr = [1, 3, 5, 7, 9]
[print(val) for val in arr]
List comprehensions are very powerful and can make coding very easy once mastered, so make sure you spend some time practicing them well.
3. Using In-Line Lambda Functions to Traverse a List
Usually, we declare functions in Python using the def keyword and have to provide a dedicated function body and header. Lambda functions are a powerful Python feature, making it much easier to write simple, shorter code. They have no name and can only contain a single expression. However, you can pass any number of parameters to a lambda function.
When combined with the map() method, the lambda function can effectively work as a for loop. To print a list of numbers using a combination of lambda functions and map():
arr = [1, 3, 4, 5, 6, 7, 8]
myFun = list(map(lambda z:z, arr))
print(myFun)
Python Loops Are Simple but Ubiquitous
Loops are essential in every programming language and Python is no different. Most programs you write will include a loop at some point, in one form or another.
This goes two-fold if you want to use Python for data science or machine learning projects.
Source: makeuseof