Java, Python, Quick solutions, Uncategorized

How to solve: pick elements from one list, that indexes are stored in second list

Today I am going to show you how to create a list combined with those elements from one list, that have indexes collected in the second list. For my example I will use python, because I have a little contact with it recently at my work.

def main():
    x = ['a', 'b', 'c', 'd', 'e']
    y = [1, 2, 3]
    z = [x[_] for _ in y]

if __name__ == "__main__":

Script presented above solves exactly the issue, which was presented in the topic.  You may ask, what underscore (‘_’) sign means in this case. It represents each and every element in the list and helps to iterate over them without necessity of describing it in a direct way. It can be substituted with another variable crated in place by parser. The same thing is achieved in stream API of Java 8 with lambdas, but single underscore sign is not allowed it this case:

IntStream.range(1, 4).map(_a -> _a * 2).forEach(System.out::print);

Python code should print list containing three elements like below:

[‘b’, ‘c’, ‘d’]