Python list get elements by index

Find elements of a list by indices in Python

Consider two lists. The elements in the second list are numbers which needs to be considered as index position for elements of the first list. For this scenario we have the below python programs.

With map and getitem

We can use the getitem magic method is used to access the list items. We can use it along with the map function, so that we get the result from first list which takes the elements from second list as its indics.

Example

listA = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] listB = [0, 1,3] print("Given list A:",listA) print("Given list B:",listB) res=list(map(listA.__getitem__, listB)) print("Result :",res)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] Given list B: [0, 1, 3] Result : ['Mon', 'Tue', 'Thu']

With itemgetter

The operator module provides itemgetter method which can be used for this purpose. In the program below we expand the second list as indices and apply the itemgetter function to get the corresponding elements from the list.

Читайте также:  Кнопка

Example

from operator import itemgetter listA = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] listB = [0, 1,3] print("Given list A:",listA) print("Given list B:",listB) res=list((itemgetter(*listB)(listA))) print("Result :",res)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] Given list B: [0, 1, 3] Result : ['Mon', 'Tue', 'Thu']

With numpy

The numpy library can achieve this by just creating an array taking the two lists as input parameters. The result is again converted into a list.

Example

import numpy as np listA = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] listB = [0, 1,3] print("Given list A:",listA) print("Given list B:",listB) res=list(np.array(listA)[listB]) print("Result :",res)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] Given list B: [0, 1, 3] Result : ['Mon', 'Tue', 'Thu']

Источник

5 Easy Ways To Extract Elements From A Python List

How To Extract Elements Png

Let’s learn the different ways to extract elements from a Python list When more than one item is required to be stored in a single variable in Python, we need to use lists. It is one of python’s built-in data functions. It is created by using [ ] brackets while initializing a variable.

In this article, we are going to see the different ways through which lists can be created and also learn the different ways through which elements from a list in python can be extracted.

1. Extract Elements From A Python List Using Index

Here in this first example, we created a list named ‘firstgrid’ with 6 elements in it. The print statement prints the ‘1’ element in the index.

firstgrid=["A","B","C","D","E","F"] print(firstgrid[1])

2. Print Items From a List Using Enumerate

Here, we created a variable named ‘vara’ and we filled the elements into the list. Then we used ‘varx’ variable to specify the enumerate function to search for ‘1,2,5’ index positions.

vara=["10","11","12","13","14","15"] print([varx[1] for varx in enumerate(vara) if varx[0] in [1,2,5]])

3. Using Loops to Extract List Elements

You can also Extract Elements From A Python List using loops. Let’s see 3 methods to pull individual elements from a list using loops.

Method 1:

Directly using a loop to search for specified indexes.

vara=["10","11","12","13","14","15"] print([vara[i] for i in (1,2,5)])

Method 2:

Storing list and index positions into two different variables and then running the loop to search for those index positions.

elements = [10, 11, 12, 13, 14, 15] indices = (1,1,2,1,5) result_list = [elements[i] for i in indices] print(result_list)

Method 3:

In this example, we used a different way to create our list. The range function creates a list containing numbers serially with 6 elements in it from 10 to 15.

numbers = range(10, 16) indices = (1, 1, 2, 1, 5) result = [numbers[i] for i in indices] print(result)

4. Using Numpy To View Items From a List

We can also use the popular NumPy library to help us Extract Elements From A Python List. Let’s see how that can be done here using two different methods.

Method 1:

Here, we used the numpy import function to print the index specified in variable ‘sx’ from the elements present in list ‘ax’ using np.array library function.

ax = [10, 11, 12, 13, 14, 15]; sx = [1, 2, 5] ; import numpy as np print(list(np.array(ax)[sx]))

Method 2:

This example uses variable storing index positions and another variable storing numbers in an array. The print statement prints the index positions stored in variable ‘sx’ with respect to a variable containing the list – ‘ay’.

sx = [1, 2, 5]; ay = np.array([10, 11, 12, 13, 14, 15]) print(ay[sx])

5. Extract Elements Using The index function

vara=["10","11","12","13","14","15"] print([vara[index] for index in (1,2,5,20) if 0 

Conclusion

This article explains in great detail the different methods available to search and extract elements from a python list. We learned in this article, how lists are made, the different types of python functions through which elements are extracted from the list. It is hoped that this article might have helped you.

Источник

How to Get List Element By Index And Slice Using Python

In this tutorial, learn how to get list element by index in Python. The short answer is: use the index operator ( [] ) and pass the index value of the element as the argument. You can also get all the elements within range using the Python slice operator( [:] ). Access the item of the list with the different methods given here.

You can get a single element or more than a single element within the range. By using the loop of Python, you can access all the elements of the list. You may also like to read how to loop over the Python list variable.

Get Single List Element By Index in Python

If you want to get the single element of the list in Python. You have to use the Python index operator which starts the element from zero(0). To get more items, you have to use the index again with the index value of the element.

The above example showing the elements of the list that is at index 1. The example using the print statement to print the accessed element in the output.

However, the above example provides you only a single element. In order to get multiple elements, you have to use the Python slice operator( [] ).

Bonus: download a Free Python cheat sheet that will show you 20+ most important examples to learn in Python.

Access List Element Within Range in Python

The slice operator( [] ) gives you all the elements within a certain range. The range requires two arguments to access an element within that range. The first argument is the starting index and the second argument is the end index value. However, you will get the value located to the previous index and not the end index value.

Источник

How to Extract an Element from a List in Python

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

  1. Python extract number from list
  2. Python extract string from list
  3. Python select list elements by index
  4. Python select elements from list by condition
  5. How to select the last element in a list python
  6. 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('.')[1]) 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)

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!

Источник

Оцените статью