OKPEDIA PYTHON LISTA EN

How to extract elements from Python list

You can extract an element or multiple elements from a list or any other iterable object in python.

How to extract an item from the list

To extract an element from the python list, enter the index of the element in square brackets.

namelist[x]

The argument x is the positive integer indicating the position (index) of an element in the index.

The index of the first element of the list is zero, the index of the second element is one, etc.

The argument can also be a range of elements between a minimum index and a maximum index.

Note. The extraction does not delete the item from the list. The pop method is used to extract and remove the element.

Example

Given the following list

lista=["A","B","C","D","E","F"]

To extract and print the second element

print(lista[1])

The output result is

'B'

The second element of the list is 'B'.

How to extract two or more items from the list

To extract a group of elements from the list, insert an interval by slicing.

namelist[start:to]

The first argument "start" is the initial item (included) and the second argument is the final item (excluded).

The extremes are separated by colon (:)

Example 1

To extract a range of elements from the first to the third, indicate the first and last position

x=list[0:3]

The first position of the interval is included while the second is excluded from the selection.

The first three elements of the list are assigned to the variable x.

['A', 'B', 'C']

The variable x is also a list.

Example 2

To extract the last two elements of a list

x=list[-2:]

In this case the starting index -2 is relative while the end index is not indicated.

The extraction of the elements starts from the penultimate element of the list.

The content of the variable x is as follows:

['E', 'F']

https://how.okpedia.org/en/python/how-to-extract-elements-from-python-list


Report us an error or send a suggestion to improve this page


Python List


FacebookTwitterLinkedinLinkedin