How to Extract an Element from a List in Python | Extract an element in the sense to obtain a particular element from the list, to achieve this python provides several predefined methods and functions. Also See:- How to Find the Length of a List in Python
We will see these below Python program examples:–
- Python extract number from list
- Python extract string from list
- Python select list elements by index
- Python select elements from list by condition
- How to select the last element in a list python
- Write a python program to select an item randomly from a list
Python Extract Number from List
Here, we extract a number from the list string, we have used the split() method to extract the numbers. split() is a predefined method in python which cuts the specified character and returns other characters in the list.
list = ['Rs. 3', 'Rs. 8', 'Rs. 80', 'Rs. 25'] print("Given list : " + str(list)) res = [int(sub.split('.')) for sub in list] print("List after extraction: " + str(res))
Given list : [‘Rs. 3’, ‘Rs. 8’, ‘Rs. 80’, ‘Rs. 25’]
List after extraction: [3, 8, 80, 25]
Python Extract String from List
Now, we extract a string from the list, we use for loop we find the match, hence it checks for the particular substring and returns the string.
list = ['Mark', 'Hark', 'Cark', 'Mack'] match = [s for s in list if "ark" in s] print(match)
[‘Mark’, ‘Hark’, ‘Cark’]
How to Extract an Element from a List in Python by Index
We extract the elements in the list by specifying the index. We use for loop and iterate over the list and extract the element specified.
list = [11, 20, 23] indices = [0, 2] elements =  for index in indices: elements.append(list[index]) print(elements)
Python Select Elements from List by Condition
Now, we will use some conditions to select the elements in the list. In the program below we extract the elements which are divisible by 3 that is by using for and if loop we find mod of 3 and then print the elements.
list = [3, 6, 49, 12, 18] for i in list: if i % 3 == 0: print(i)
How to Select the Last Element in a List Python
To get the last element in python just use the list[-1] in the print statement it prints the last element, this is called slicing in python. By slicing, we can get any element easily.
list = [3, 6, 49, 12, 18] print(list[-1])
Write a Python Program to Select an Item Randomly from a List
To print an element in a list randomly use random.choice() method in the random module available in python which takes a list as a parameter and returns some random element from the list.
import random list = [3, 6, 49, 12, 18] print(random.choice(list))
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!