Python Getting sublist element till N

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to write a program that returns a sublist element till nth sublist in a list. Let's say we have the following list with 5 sublists.

[['Python', 'Java'], ['C', 'Pascal'], ['Javascript', 'PHP'], ['C#', 'C++'], ['React', 'Angular']] Now, we have to get the first element from the first three sublists. We can get the elements different approaches. Let's see some of them.

Loops

More generic and first thought of the most of programmers is to use loops. Let's see the code using loops.

Example

 Live Demo

# initializing the list and N
random_list = [['Python', 'Java'], ['C', 'Pascal'], ['Javascript', 'PHP'], ['C#
C++'], ['React', 'Angular']]
N = 3
# empty list to store final elements from the sublists
desired_elements = []
# iterating over the list till 3rd element
for i in range(N):
   # storing the first element from the sublist
   desired_elements.append(random_list[i][0])
# printing the elements
print(desired_elements)

Output

If you run the above code, then you will get the following result.

['Python', 'C', 'Javascript']

We can use the list comprehensions in place of for loop. Let's see the same code using list comprehensions.

Example

 Live Demo

# initializing the list and N
random_list = [['Python', 'Java'], ['C', 'Pascal'], ['Javascript', 'PHP'], ['C#
C++'], ['React', 'Angular']]
N = 3
# getting first element from the sublists
desired_elements = [sublist[0] for sublist in random_list[:N]]
# printing the elements
print(desired_elements)

Output

If you run the above code, then you will get the following result.

['Python', 'C', 'Javascript']

Using Built-in Methods

Python provides a lot of built-in modules and methods. Let's use them to solve our problem.are going to use the map, itemgetter, and islice methods to achieve the output as expected.Let's see the code.

Example

 Live Demo

# importing the required methods
import operator # for itemgetter
import itertools # for islice
# initializing the list and N
random_list = [['Python', 'Java'], ['C', 'Pascal'], ['Javascript', 'PHP'], ['C#
C++'], ['React', 'Angular']]
N = 3
# getting first element from the sublists
desired_elements = list(map(operator.itemgetter(0), itertools.islice(random_list, N)))
# printing the elements
print(desired_elements)

Output

If you run the above code, then you will get the following result.

['Python', 'C', 'Javascript']

Conclusion

You can take any element in place of the first element. We have taken the first element for the demonstration. If you have any doubts in the tutorial, mention them in the comment section.

raja
Updated on 06-Jul-2020 09:35:59

Advertisements