How do I get one element from a list in Python?

Get Specific Elements from List by Index

To access any item in a list use the brackets operator with the index of the item you want to retrieve. E.g. if we want to access the point (4, 5) from our list ps we write:

# list of points from the 2D space ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] point = ps[2]


The indices start at 0, therefore the third element’s index is 2. In Python it is also possible to count from back to front using negative indices.
This is very handy, especially for retrieving the last or second last element.
The index of a list’s last element is -1, the index of the second last is -2 and so on.

Try it out:

Get Specific Elements from List using pop()

If you want to access and remove an item from a list, call the pop() method with
the index of the element. If you don’t pass a value for the index, the pop() method
returns and removes the last element from the list.
This is how you get and remove the item (4, 5) using the pop() method:

# list of points from the 2D space ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] item = ps.pop(2) print(ps) # [(2, 4), (-1, 7), (3, -4), (-1, -5)]

Now, the variable item has the value (4, 5).

Get Specific Elements from List with Slicing

To get a continuous range of elements from a list, use slicing.
Slicing also uses the brackets operator with a start and end index.
As code it looks as follows:

ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] items = ps[2:4]


where the first number before the colon (:) is the start index and the second number,
after the colon, is the end index. The start index is included, the end index is excluded.
In our example items = ps[2:4]the start index is 2, the end index is 4.
Since the start index is included, we get the elements at indices 2 and 3.
The end index is not included, therefore the element at index 4 is not included.
Thus, the value of the variable items will be [(4, 5), (3, -4)]

With slicing you can use a third parameter step to get items in a range with
regular distances. Read more about slicing in our detailed article.

Python Lists and List Manipulation

Michael Galarnyk

May 29, 2017·6 min read

Python Lists and List Manipulation Video

Before starting, I should mention that the code in this blog post and in the video above is available on my github.

Python | Get first and last elements of a list

Sometimes, there might be a need to get the range between which a number lies in the list, for such applications we require to get the first and last element of the list. Let’s discuss certain ways to get the first and last element of the list.

Method #1 : Using list index
Using the list indices inside the master list can perform this particular task. This is most naive method to achieve this particular task one can think of.




# Python3 code to demonstrate

# to get first and last element of list

# using list indexing

# initializing list

test_list = [1, 5, 6, 7, 4]

# printing original list

print ("The original list is : " + str(test_list))

# using list indexing

# to get first and last element of list

res = [ test_list[0], test_list[-1] ]

# printing result

print ("The first and last element of list are : " + str(res))

Output: The original list is : [1, 5, 6, 7, 4] The first and last element of list are : [1, 4]


Method #2 : Using List slicing
One can also make use of list slicing technique to perform the particular task of getting first and last element. We can use step of whole list to skip to the last element after the first element.




# Python3 code to demonstrate

# to get first and last element of list

# using List slicing

# initializing list

test_list = [1, 5, 6, 7, 4]

# printing original list

print ("The original list is : " + str(test_list))

# using List slicing

# to get first and last element of list

res = test_list[::len(test_list)-1]

# printing result

print ("The first and last element of list are : " + str(res))

Output: The original list is : [1, 5, 6, 7, 4] The first and last element of list are : [1, 4]


Method #3 : Using list comprehension
List comprehension can be employed to provide a shorthand to the loop technique to find first and last element of the list. Naive method of finding is converted to a single line using this method.




# Python3 code to demonstrate

# to get first and last element of list

# using list comprehension

# initializing list

test_list = [1, 5, 6, 7, 4]

# printing original list

print ("The original list is : " + str(test_list))

# using list comprehension

# to get first and last element of list

res = [ test_list[i] for i in (0, -1) ]

# printing result

print ("The first and last element of list are : " + str(res))

Output: The original list is : [1, 5, 6, 7, 4] The first and last element of list are : [1, 4]




Article Tags :

Python

Python Programs

Python list-programs

Read Full Article

Check if element exists in list in Python

List is an important container in python as if stores elements of all the datatypes as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses one of the basic list operations of ways to check the existence of elements in the list.

Method 1: Naive Method

In Naive method, one easily uses a loop that iterates through all the elements to check the existence of the target element. This is the simplest way to check the existence of the element in the list.

Method 2: Using in

Python is the most conventional way to check if an element exists in a list or not. This particular way returns True if an element exists in the list and False if the element does not exist in the list. List need not be sorted to practice this approach of checking.

Code #1: Demonstrating to check the existence of an element in the list using the Naive method and in.

Python3




# Python code to demonstrate

# checking of element existence

# using loops and in

# Initializing list

test_list = [ 1, 6, 3, 5, 3, 4 ]

print("Checking if 4 exists in list ( using loop ) : ")

# Checking if 4 exists in list

# using loop

for i in test_list:

if(i == 4) :

print ("Element Exists")

print("Checking if 4 exists in list ( using in ) : ")

# Checking if 4 exists in list

# using in

if (4 in test_list):

print ("Element Exists")

Output :



Checking if 4 exists in list ( using loop ) : Element Exists Checking if 4 exists in list ( using in ) : Element Exists

Method 3 : Using set() + in

Converting the list into the set and then using in can possibly be more efficient than only using in. But having efficiency for a plus also has certain negatives. One among them is that the order of list is not preserved, and if you opt to take a new list for it, you would require to use extra space. Another drawback is that set disallows duplicity and hence duplicate elements would be removed from the original list.

Method 4 : Using sort() + bisect_left()

The conventional binary search way of testing element existence, hence list has to be sorted first and hence not preserving the element ordering. bisect_left() returns the first occurrence of the element to be found and has worked similarly to lower_bound() in C++ STL.

Note: The bisect function will only state the position of where to insert the element but not the details about if the element is present or not.

Code #2 : Demonstrating to check existence of element in list using set() + in and sort() + bisect_left().

Python3




# Python code to demonstrate

# checking of element existence

# using set() + in

# using sort() + bisect_left()

from bisect import bisect_left ,bisect

# Initializing list

test_list_set = [ 1, 6, 3, 5, 3, 4 ]

test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]

print("Checking if 4 exists in list ( using set() + in) : ")

# Checking if 4 exists in list

# using set() + in

test_list_set = set(test_list_set)

if 4 in test_list_set :

print ("Element Exists")

print("Checking if 4 exists in list ( using sort() + bisect_left() ) : ")

# Checking if 4 exists in list

# using sort() + bisect_left()

test_list_bisect.sort()

if bisect_left(test_list_bisect, 4)!=bisect(test_list_bisect, 4):

print ("Element Exists")

else:

print("Element doesnt exist")

Method 5 : Using count()

We can use the in-built python List method, count(), to check if the passed element exists in List. If the passed element exists in the List, count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

Code #3 : Demonstrating to check the existence of elements in the list using count().

Python3




"""

Python code to demonstrate

checking of element existence

using List count() method

"""

# Initializing list

test_list = [10, 15, 20, 7, 46, 2808]

print("Checking if 15 exists in list")

# number of times element exists in list

exist_count = test_list.count(15)

# checking if it is more then 0

if exist_count > 0:

print("Yes, 15 exists in list")

else:

print("No, 15 does not exists in list")




Article Tags :

Python

Python list-programs

python-list

Practice Tags :

python-list

Read Full Article

Python lists

last modified December 15, 2021

In this part of the Python programming tutorial, we cover Python lists in more detail.

Python - Lists

Advertisements


Previous Page

Next Page

The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.

Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.

There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.

Getting the first element of a List in Python

python1min read

In this tutorial, we are going to learn about how to get the first element of a list in Python.

Consider, we have the following list:

numList = [12, 13, 14, 15, 16]

To access the first element (12) of a list, we can use the subscript syntax [ ] by passing an index 0.

In Python lists are zero-indexed, so the first element is available at index 0.

Here is an example:

numList = [12, 13, 14, 15, 16] firstElement = num_list[0] print(firstElement) # 12

Similarly, we can also use the slicing syntax [:1] to get the first element of a list in Python.

numList = [12, 13, 14, 15, 16] firstElement = numList[:1] print(firstElement) # 12

  • Share:

Video liên quan

Postingan terbaru

LIHAT SEMUA