- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to find a sublist where first and last values are same in Python

Suppose we have a list of numbers called nums, we have to find the number of sublists where the first element and the last element are same.

So, if the input is like nums = [10, 15, 13, 10], then the output will be 5, as the sublists with same first and last element are: [10], [15], [13], [10], [10, 15, 13, 10].

To solve this, we will follow these steps −

num_sublists := size of nums

d := an empty map

for each n in nums, do

d[n] := d[n] + 1

for each number k and corresponding frequency v of elements in d, do

if v is not same as 1, then

num_sublists := num_sublists +(quotient of (v-1) *(v) /2)

return num_sublists

Let us see the following implementation to get better understanding −

## Example

from collections import defaultdict class Solution: def solve(self, nums): num_sublists = len(nums) d = defaultdict(int) for n in nums: d[n] += 1 for k,v in d.items(): if v != 1: num_sublists += (v-1)*(v)//2 return num_sublists ob = Solution() nums = [10, 15, 13, 10] print(ob.solve(nums))

## Input

[10, 15, 13, 10]

## Output

5

- Related Articles
- Program to find length of longest contiguous sublist with same first letter words in Python
- Program to find number of quadruples for which product of first and last pairs are same in Python
- Program to find number of operations needed to make pairs from first and last side are with same sum in Python
- Program to pack same consecutive elements into sublist in Python
- Python program to interchange first and last elements in a list
- Python program to find Sum of a sublist
- Program to find size of sublist where product of minimum of A and size of A is maximized in Python
- Display records where first and last name begins with the same letter in MySQL
- Python Program to Form a New String where the First Character and the Last Character have been Exchanged
- Program to find length of longest sublist where difference between min and max smaller than k in Python
- Program to find the size of the longest sublist where car speed is constant in python
- Python program to get first and last elements from a tuple
- Python Program to get first and last element from a Dictionary
- Program to find length of shortest sublist with maximum frequent element with same frequency in Python
- Python Program to Swap the First and Last Value of a List

Advertisements