How do you find individual elements in a list?

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.

Python | Get elements till particular element in list

Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using index[] + list slicing
This problem can be solved using the combination of these functions. The index[] can be used to find the index of desired element and list slicing can perform the remaining task of getting the elements.




# Python3 code to demonstrate working of

# Get elements till particular element in list

# using index[] + list slicing

# initialize list

test_list = [1, 4, 6, 8, 9, 10, 7]

# printing original list

print["The original list is : " + str[test_list]]

# declaring elements till which elements required

N = 8

# Get elements till particular element in list

# using index[] + list slicing

temp = test_list.index[N]

res = test_list[:temp]

# printing result

print["Elements till N in list are : " + str[res]]

Output : The original list is : [1, 4, 6, 8, 9, 10, 7] Elements till N in list are : [1, 4, 6]

Method #2 : Using generator
This task can also be performed using the generator function which uses yield to get the elements just till the required element and breaks the yields after that element.




# Python3 code to demonstrate working of

# Get elements till particular element in list

# using generator

# helper function to perform task

def print_ele[test_list, val]:

for ele in test_list:

if ele == val:

return

yield ele

# initialize list

test_list = [1, 4, 6, 8, 9, 10, 7]

# printing original list

print["The original list is : " + str[test_list]]

# declaring elements till which elements required

N = 8

# Get elements till particular element in list

# using generator

res = list[print_ele[test_list, N]]

# printing result

print["Elements till N in list are : " + str[res]]

Output : The original list is : [1, 4, 6, 8, 9, 10, 7] Elements till N in list are : [1, 4, 6]




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 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.

FOR and IN

Python's *for* and *in* constructs are extremely useful, and the first use of them we'll see is with lists. The *for* construct -- for var in list -- is an easy way to look at each element in a list [or other collection]. Do not add or remove from the list during iteration.

squares = [1, 4, 9, 16] sum = 0 for num in squares: sum += num print sum ## 30

If you know what sort of thing is in the list, use a variable name in the loop that captures that information such as "num", or "name", or "url". Since Python code does not have other syntax to remind you of types, your variable names are a key way for you to keep straight what is going on.

The *in* construct on its own is an easy way to test if an element appears in a list [or other collection] -- value in collection -- tests if the value is in the collection, returning True/False.

list = ['larry', 'curly', 'moe'] if 'curly' in list: print 'yay'

The for/in constructs are very commonly used in Python code and work on data types other than list, so you should just memorize their syntax. You may have habits from other languages where you start manually iterating over a collection, where in Python you should just use for/in.

You can also use for/in to work on a string. The string acts like a list of its chars, so for ch in s: print ch prints all the chars in a string.

Range

The range[n] function yields the numbers 0, 1, ... n-1, and range[a, b] returns a, a+1, ... b-1 -- up to but not including the last number. The combination of the for-loop and the range[] function allow you to build a traditional numeric for loop:

## print the numbers from 0 through 99 for i in range[100]: print i

There is a variant xrange[] which avoids the cost of building the whole list for performance sensitive cases [in Python 3, range[] will have the good performance behavior and you can forget about xrange[]].

While Loop

Python also has the standard while-loop, and the *break* and *continue* statements work as in C++ and Java, altering the course of the innermost loop. The above for/in loops solves the common case of iterating over every element in a list, but the while loop gives you total control over the index numbers. Here's a while loop which accesses every 3rd element in a list:

## Access every 3rd element in a list i = 0 while i < len[a]: print a[i] i = i + 3

List Methods

Here are some other common list methods.

  • list.append[elem] -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
  • list.insert[index, elem] -- inserts the element at the given index, shifting elements to the right.
  • list.extend[list2] adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend[].
  • list.index[elem] -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear [use "in" to check without a ValueError].
  • list.remove[elem] -- searches for the first instance of the given element and removes it [throws ValueError if not present]
  • list.sort[] -- sorts the list in place [does not return it]. [The sorted[] function shown later is preferred.]
  • list.reverse[] -- reverses the list in place [does not return it]
  • list.pop[index] -- removes and returns the element at the given index. Returns the rightmost element if index is omitted [roughly the opposite of append[]].

Notice that these are *methods* on a list object, while len[] is a function that takes the list [or string or whatever] as an argument.

list = ['larry', 'curly', 'moe'] list.append['shemp'] ## append elem at end list.insert[0, 'xxx'] ## insert elem at index 0 list.extend[['yyy', 'zzz']] ## add list of elems at end print list ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz'] print list.index['curly'] ## 2 list.remove['curly'] ## search and remove that element list.pop[1] ## removes and returns 'larry' print list ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']

Common error: note that the above methods do not *return* the modified list, they just modify the original list.

list = [1, 2, 3] print list.append[4] ## NO, does not work, append[] returns None ## Correct pattern: list.append[4] print list ## [1, 2, 3, 4]

List Build Up

One common pattern is to start a list a the empty list [], then use append[] or extend[] to add elements to it:

list = [] ## Start as the empty list list.append['a'] ## Use append[] to add elements list.append['b']

List Slices

Slices work on lists just as with strings, and can also be used to change sub-parts of the list.

list = ['a', 'b', 'c', 'd'] print list[1:-1] ## ['b', 'c'] list[0:2] = 'z' ## replace ['a', 'b'] with ['z'] print list ## ['z', 'c', 'd']

Video liên quan

Bài mới nhất

Chủ Đề