Python Program that prints elements common at specified index of list elements
Last Updated :
18 May, 2023
Given a list of strings, the task is to write a Python program to extract all characters that are same at a specified index of each element of a list.
Illustration:
Input : test_list = ["geeks", "weak", "beak", "peek"]
Output : ['e', 'k']
Explanation : e and k are at same at an index on all strings.
Input : test_list = ["geeks", "weak", "beak", "peer"]
Output : ['e']
Explanation : e is at same at an index on all strings.
Method 1 : Using min(), len() and loop
In this, initially, a minimum length string is extracted to check indices to iterate to ensure all indices in strings. Then each index is checked for similar character using loop, if found, character is appended to result.
Python3
# initializing Matrix
test_list = ["geeks", "weak", "beak", "peek"]
# printing original list
print("The original list is : " + str(test_list))
# getting min length string
min_len = min(len(ele) for ele in test_list)
res = []
for idx in range(0, min_len):
flag = True
for ele in test_list:
# checking for all equal columns
if ele[idx] != test_list[0][idx]:
flag = False
break
if flag:
res.append(test_list[0][idx])
# printing result
print("Extracted similar characters : " + str(res))
OutputThe original list is : ['geeks', 'weak', 'beak', 'peek']
Extracted similar characters : ['e', 'k']
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Method 2 : Using all(), min(), len() and loop
In this, we perform the task of checking all elements to match using all(), reducing a nested loop, increasing readability.
Python3
# initializing Matrix
test_list = ["geeks", "weak", "beak", "peek"]
# printing original list
print("The original list is : " + str(test_list))
# getting min length string
min_len = min(len(ele) for ele in test_list)
res = []
for idx in range(0, min_len):
# using all() for condition injection
if all(ele[idx] == test_list[0][idx] for ele in test_list):
res.append(test_list[0][idx])
# printing result
print("Extracted similar characters : " + str(res))
OutputThe original list is : ['geeks', 'weak', 'beak', 'peek']
Extracted similar characters : ['e', 'k']
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method 3: Using set comprehension + zip() function
Python3
test_list = ["geeks", "weak", "beak", "peek"]
# printing original list
print("The original list is : " + str(test_list))
# Transpose the list of strings into a list of lists of characters
char_lists = [list(string) for string in test_list]
# Use zip to iterate over the columns of characters
columns = zip(*char_lists)
# Use a set comprehension to select only columns where all characters are equal
res = [char[0] for char in columns if len(set(char)) == 1]
# printing result
print("Extracted similar characters : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original list is : ['geeks', 'weak', 'beak', 'peek']
Extracted similar characters : ['e', 'k']
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method 4: Using set intersection and loop
Approach:
- Initialize a set with the characters of the first string in the list.
- Now use the intersection_update method to only keep the common characters between the current set and each string in the list, one by one.
- Finally, we convert the set back to a list and print the result.
Example:
Python
# Initializing list
test_list = ["geeks", "weak", "beak", "peek"]
# Printing original list
print("The original list is : " + str(test_list))
res = set(test_list[0])
for ele in test_list[1:]:
res.intersection_update(ele)
res = list(res)
# Printing result
print("Extracted similar characters : " + str(res))
OutputThe original list is : ['geeks', 'weak', 'beak', 'peek']
Extracted similar characters : ['k', 'e']
Time Complexity: O(n)
Auxiliary Space: O(m), where m is the length of the longest string in the list.
Method 5: Using Counter from collections module
- The program first imports the Counter class from the collections module. The Counter class is a dictionary subclass which helps count the occurrences of items in a list.
- The program then creates a list called test_list that contains four strings: "geeks", "weak", "beak", and "peek".
- The program prints the original list using the print() function and the str() function to convert the list to a string: "The original list is : " + str(test_list).
- The program then initializes a Counter object called common_chars with the characters from the first string in test_list using the Counter() constructor.
- The program then loops through the remaining strings in test_list using a for loop with string as the loop variable.
- Inside the for loop, the program updates the common_chars object to contain only the characters that are common between the current string and common_chars using the &= operator.
- After the for loop, the program creates a list called res by calling the elements() method on common_chars and then converting the result to a list using the list() constructor.
- Finally, the program prints the list of common characters using the print() function and the str() function: "Extracted similar characters : " + str(res)".
Python3
from collections import Counter
test_list = ["geeks", "weak", "beak", "peek"]
print("The original list is : " + str(test_list))
common_chars = Counter(test_list[0])
for string in test_list[1:]:
common_chars &= Counter(string)
res = list(common_chars.elements())
print("Extracted similar characters : " + str(res))
OutputThe original list is : ['geeks', 'weak', 'beak', 'peek']
Extracted similar characters : ['e', 'k']
Time complexity: O(n*m), where n is the length of the list and m is the length of the longest string in the list.
Auxiliary space: O(K), where k is the number of unique characters in the list of strings.
Method 6: Using reduce() from functools module
Python3
from functools import reduce
# Initializing list
test_list = ["geeks", "weak", "beak", "peek"]
# Pnting original list
print("The original list is: " + str(test_list))
res = list(reduce(lambda x, y: set(x) & set(y), test_list))
# Printing result
print("Extracted similar characters: " + str(res))
OutputThe original list is: ['geeks', 'weak', 'beak', 'peek']
Extracted similar characters: ['e', 'k']
Time complexity: O(n * m)
Auxiliary space: O(k)
Similar Reads
Python program to find the frequency of the elements which are common in a list of strings Given list of strings. The task is to find the frequency of the elements which are common in all strings given in the list of strings. Examples: Input : test_list = ["gegek", "gfgk", "kingg"] Output : {'g': 2, 'k': 1} Explanation : g occurs twice in all Strings. Input : test_list = ["gefgek", "gfgk"
3 min read
Python Program to Find Most common elements set Given a List of sets, the task is to write a Python program tocompare elements with argument set, and return one with maximum matching elements. Examples: Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {9, 6, 5, 3}Output : {9, 3, 5, 7}Explanation : Resultant
5 min read
Python program to return rows that have element at a specified index Given two Matrices, the task is to write a Python program that can extract all the rows from both matrices which have similar elements at their Kth index, mapped at similar row positions. Examples: Input : test_list1 = [[1, 8, 3], [9, 2, 0], [6, 4, 4], [6, 4, 4]], test_list2 = [[1, 9, 3], [8, 2, 3],
5 min read
Python program to remove duplicate elements index from other list Given two lists, the task is to write a Python program to remove all the index elements from 2nd list which are duplicate element indices from 1st list. Examples: Input : test_list1 = [3, 5, 6, 5, 3, 7, 8, 6], test_list2 = [1, 7, 6, 3, 7, 9, 10, 11] Output : [1, 7, 6, 9, 10] Explanation : 3, 7 and 1
7 min read
Python - Print all common elements of two lists Finding common elements between two lists is a common operation in Python, especially in data comparison tasks. Python provides multiple ways to achieve this, from basic loops to set operations. Let's see how we can print all the common elements of two listsUsing Set Intersection (Most Efficient)The
3 min read
Python Program to repeat elements at custom indices Given a List, the following program repeats those elements which are at a custom index, these custom indices are provided to it as a separate list. Input : test_list = [4, 6, 7, 3, 1, 9, 2, 19], idx_list = [3, 1, 6] Output : [4, 6, 6, 7, 3, 3, 1, 9, 2, 2, 19] Explanation : All required index element
6 min read
Python | Find common elements in list of lists The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let's discuss certain ways in which this operation can be
6 min read
Python | Print the common elements in all sublists Given a list of lists, the task is to find the elements which are common in all sublist. There are various approaches to do this task. Let's discuss the approaches one by one. Method #1: Using set Python3 # Python code to find duplicate element in all # sublist from list of list # List of list initi
3 min read
Find Common elements in three Lists using Sets - Python We are given three lists we need to find common elements in all three lists using sets. For example a = [1, 2, 3, 4], b = [2, 3, 5, 6] and c = [1, 2, 3, 7]. We need to find all common elements so that resultant output should be {2, 3}.Using set.intersection()set.intersection() method finds common el
3 min read
Python - Check if two lists have at-least one element common Checking if two lists share at least one common element is a frequent task when working with datasets, filtering, or validating data. Python offers multiple efficient ways to solve this depending on the size and structure of the lists.Using set IntersectionConverting both lists into sets and finding
3 min read