DEV Community

aKuad
aKuad

Posted on

Alternative of 'for' in Python

JavaScript version:

https://dev.to/akuad/alternative-of-for-in-javascript-3p71/edit

Introduction

There are some cases of processing elements in list. Basically solution is process with for.

Actually, there are other solutions without using for. Them can reduce code and keep code in simple.

Note: In some cases, for can be the best solution.

Tutorial: lambda expression

These codes will be take same behavior.

def func(e):
  return e*2
Enter fullscreen mode Exit fullscreen mode
lambda e: e*2
Enter fullscreen mode Exit fullscreen mode

By using lambda:, you can omit def, function name and return.

Make an Array what elements processed

E.g. multiplex x2

in_list  = [1, 2, 3, 4]
out_list = []

for e in in_list:
  out_list.append(e * 2)
# out_list: [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode
in_list  = [1, 2, 3, 4]
out_list = map(lambda e: e*2, in_list)
# out_list: [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Reference: map()

If you good for list comprehensions, it can be more few code.

in_list  = [1, 2, 3, 4]
out_list = [e*2 for e in in_list]
Enter fullscreen mode Exit fullscreen mode

Extract elements what match to a condition

E.g. Extract even numbers from Array

array      = [1, 2, 3, 4]
array_even = []

for e in array:
  if e % 2 == 0:
    array_even.append(e)
# array_even: [2, 4]
Enter fullscreen mode Exit fullscreen mode
array      = [1, 2, 3, 4]
array_even = filter(lambda e: (e % 2) == 0, array)
# array_even: [2, 4]
Enter fullscreen mode Exit fullscreen mode

Reference: filter()

Check is a value in Array

E.g. Check is input string day-name

in_text   = "mon"
day_names = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]

is_input_true = False
for e in day_names:
  if in_text == e:
    is_input_true = True
    break
# is_input_true: True
Enter fullscreen mode Exit fullscreen mode
in_text   = "mon"
day_names = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]

is_input_true = in_text in day_names
# is_input_true: true
Enter fullscreen mode Exit fullscreen mode

Reference: Membership test operations

Conclusion

Sometimes let’s see document (language reference, command help and so on).

You can find good functions, methods or options.

Top comments (0)