Count sublist in list Python

Python – Count frequency of Sublist in given list

Given a List and a sublist, count occurrence of sublist in list.

Input : test_list = [4, 5, 3, 5, 7, 8, 3, 5, 7, 2, 3, 5, 7], sublist = [3, 5, 7]
Output : 3
Explanation : 3, 5, 7 occurs 3 times.

Input : test_list = [4, 5, 3, 5, 8, 8, 3, 2, 7, 2, 3, 6, 7], sublist = [3, 5, 7]
Output : 0
Explanation : No occurrence found.

Method #1 : Using list comprehension + slicing

In this, we test for each sublist of list extracted using slicing, if found, the element is added to list, at last length of list is computed using len().






# Python3 code to demonstrate working of

# Sublist Frequency

# Using list comprehension + slicing

# initializing list

test_list = [4, 5, 3, 5, 7, 8, 3, 5, 7, 2, 7, 3, 2]

# printing original list

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

# initializing Sublist

sublist = [3, 5, 7]

# slicing is used to extract chunks and compare

res = len([sublist for idx in range(len(test_list)) if test_list[idx : idx + len(sublist)] == sublist])

# printing result

print("The sublist count : " + str(res))

Output The original list is : [4, 5, 3, 5, 7, 8, 3, 5, 7, 2, 7, 3, 2] The sublist count : 2

Method #2 : Using zip_longest() + islice() + all() + loop

In this, we perform task of slicing using islice() and check if each element is matching using all(), zip_longest() helps in mapping elements to check for equality from sublist. Loop is used to get to index match with first element of sublist in list, to make it more efficient.




# Python3 code to demonstrate working of

# Sublist Frequency

# Using zip_longest() + islice() + all() + loop

from itertools import zip_longest, islice

# initializing list

test_list = [4, 5, 3, 5, 7, 8, 3, 5, 7, 2, 7, 3, 2]

# printing original list

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

# initializing Sublist

sublist = [3, 5, 7]

# slicing is used to extract chunks and compare

res = []

idx = 0

while True:

try:

# getting to the index

idx = test_list.index(sublist[0], idx)

except ValueError:

break

# using all() to check for all elements equivalence

if all(x == y for (x, y) in zip_longest(sublist, islice(test_list, idx, idx + len(sublist)))):

res.append(sublist)

idx += len(sublist)

idx += 1

res = len(res)

# printing result

print("The sublist count : " + str(res))

Output The original list is : [4, 5, 3, 5, 7, 8, 3, 5, 7, 2, 7, 3, 2] The sublist count : 2

Count sublist in list Python




Article Tags :

Python

Python Programs

Python list-programs

Python | Count the sublists containing given element in a list

Given a list of lists, write a Python program to count the number of sublists containing the given element x.

Examples:

Input : lst = [1, 3, 5], [1, 3, 5, 7], [1, 3, 5, 7, 9]] x = 1 Output : 3 Input : lst = (['a'], ['a', 'c', 'b'], ['d']) x = 'a' Output : 2


Approach #1 : Naive Approach

Count the number of lists containing x. Initialize count to 0, then start a for loop and check if x exists in each list or not. If yes, increment count.




# Python3 Program to count number of

# list containing a certain element

# in a list of lists

def countList(lst, x):

count = 0

for i in range(len(lst)):

if x in lst[i]:

count+= 1

return count

# Driver Code

lst = (['a'], ['a', 'c', 'b'], ['d'])

x = 'a'

print(countList(lst, x))

Output:


2


Approach #2 : List comprehension (Alternative for naive)
A simple one-liner list comprehension can also do the job by simply converting the above mentioned Naive approach into one-liner for loop.




# Python3 Program to count number of

# list containing a certain element

# in a list of lists

def countList(lst, x):

return sum(x in item for item in lst)

# Driver Code

lst = (['a'], ['a', 'c', 'b'], ['d'])

x = 'a'

print(countList(lst, x))

Output: 2


Approach #3 : Using chain.from_iterable() and Counter

We can use Counter to count how many lists ‘x’ occurs in. Since we don’t want to count ‘x’ for more than once for each inner list, we’ll convert each inner list to sets. After this, join those sets of elements into one sequence using chain.from_iterable().




# Python3 Program to count number of

# list containing a certain element

# in a list of lists

from itertools import chain

from collections import Counter

def countList(lst, x):

return Counter(chain.from_iterable(set(i) for i in lst))[x]

# Driver Code

lst = (['a'], ['a', 'c', 'b'], ['d'])

x = 'a'

print(countList(lst, x))

Output: 2

Count sublist in list Python




Article Tags :

Python

Python Programs

Python list-programs

python-list

Practice Tags :

python-list

Count elements in a flat list

Suppose we have a list i.e.

# List of strings listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']
To count the elements in this list, we have different ways. Let’s explore them,

Use len() function to get the size of a list

Python provides a inbuilt function to get the size of a sequence i.e.

len(s)
Arguments:
  • s : A sequence like object like, list, string, bytes, tuple etc.

It returns the length of object i.e. count of elements in the object.

Advertisements

Now let’s use this len() function to get the size of a list i.e.

listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test'] # Get size of a list using len() length = len(listOfElems) print('Number of elements in list : ', length)
Output:
Number of elements in list : 9
How does len() function works ?

When len(s) function is called, it internally calls the __len__() function of the passed object s. Default sequential containers like list, tuple & string has implementation of __len__() function, that returns the count of elements in that sequence.

So, in our case we passed the list object to the len() function. Which internally called the __len__() of the list object, to fetch the count of elements in list.

Use list.__len__() to count elements in a list

We can directly call the __len__() member function of list to get the size of list i.e.

listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test'] # Get size of a list using list.__len__() length = listOfElems.__len__() print('Number of elements in list : ', length)
Output:
Number of elements in list : 9
Although we got the size of list using __len__() function. It is not a recommended way, we should always prefer len() to get the size of list.

Count unique sublists within list in Python

PythonServer Side ProgrammingProgramming



A Python list can also contain sublist. A sublist itself is a list nested within a bigger list. In this article we will see how to count the number of unique sublists within a given list.

Count the sublists containing given element in a list in Python

PythonServer Side ProgrammingProgramming



The elements in a given list can also be present as another string in another variable. In this article we'll see how many times a given stream is present in a given list.

“python count elements in sublists” Code Answer


python count elements in sublists

python by ZeldaIsANerd

Count sublist in list Python
on Feb 03 2021 Comment

0

Add a Grepper Answer


  • python subtract every element in list
  • how to count things in a list python
  • python find number of occurrences in list
  • python count code, Count number of occurrences of a given substring
  • get subscriber count with python
  • count occurrence in array python
  • count repeat values in python list
  • python count appearances in list
  • python counting subfolders on specific level
  • count number of subdirectories
  • find all occurrences of an element in a list python
  • count number of occurrences of all elements in list python
  • count number of each item in list python

  • python count elements in sublists
  • how to count sublist elements in python
  • count sublist in list python
  • count the elements within any sublist
  • how to count elements in sublist in python
  • count sublists
  • count number of elements in sublist python

Python List Count With Examples

Python Lists can contain objects of the same type or of different types. For example, a List can contain all items as Integer or items as integer, String, boolean etc.

The length of the list can be identified using the len() and using for loop.

Using Len() Function

In Python, you can find the length of the list using the len() function.

Use the below snippet to get the count of elements in list.

Snippet

list = ['a','b','c'] len(list)

There are 3 elements in the list. You’ll see the output as 3.

Output

3

You’ve calculated the items in the list which have the same type of values. Next, you’ll see the list with different types of items.

Count List with Different Type of Items

The example list contains one character, one number, one boolean value, and one value None which is used to denote the missing data.

However, when a list has None, it is also counted as one element while using len() function.

Snippet

list = ['a',1, True, None] len(list)

The example list has 4 values including None. Hence, you’ll see the output 4.

Output

4

This is how you can get the number of elements in the list using the len() function. This is also known as finding list length.

Next, you’ll learn how to use for loop.

Using For Loop

In this section, you’ll learn how to count the number of elements in a list using the for loop.

for loop is used to iterate over a sequence of values.

To get the number of elements in the list, you’ll iterate over the list and increment the counter variable during each iteration. Once the iteration is over, you’ll return the count variable which has the total number of elements in the list.

In the below example,

  • You’ve initialized a list with different types of values
  • Created a function which will iterate the list and count the elements
  • Printed the count using print statement.

Snippet

list = ['a',1, True, None] def get_no_of_elements(list): count = 0 for element in list: count += 1 return count print("Number of elements in the list: ", get_no_of_elements(list))

There are 4 elements in the list including the None value. Hence you’ll see output 4.

Output

Number of elements in the list: 4

This is how you can get the number of elements in a list using for loop.

Next, let us discuss the counting with condition.

5. Data Structures¶

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.