Description
stringlengths 9
105
| Link
stringlengths 45
135
| Code
stringlengths 10
26.8k
| Test_Case
stringlengths 9
202
| Merge
stringlengths 63
27k
|
---|---|---|---|---|
Python | Uncommon elements in Lists of List | https://www.geeksforgeeks.org/python-uncommon-elements-in-lists-of-list/?ref=leftbar-rightbar | # Python 3 code to demonstrate
# Uncommon elements in List
# using naive method
# initializing lists
test_list1 = [[1, 2], [3, 4], [5, 6]]
test_list2 = [[3, 4], [5, 7], [1, 2]]
# printing both lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using naive method
# Uncommon elements in List
res_list = []
for i in test_list1:
if i not in test_list2:
res_list.append(i)
for i in test_list2:
if i not in test_list1:
res_list.append(i)
# printing the uncommon
print("The uncommon of two lists is : " + str(res_list)) |
#Output : The original list 1 : [[1, 2], [3, 4], [5, 6]] | Python | Uncommon elements in Lists of List
# Python 3 code to demonstrate
# Uncommon elements in List
# using naive method
# initializing lists
test_list1 = [[1, 2], [3, 4], [5, 6]]
test_list2 = [[3, 4], [5, 7], [1, 2]]
# printing both lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using naive method
# Uncommon elements in List
res_list = []
for i in test_list1:
if i not in test_list2:
res_list.append(i)
for i in test_list2:
if i not in test_list1:
res_list.append(i)
# printing the uncommon
print("The uncommon of two lists is : " + str(res_list))
#Output : The original list 1 : [[1, 2], [3, 4], [5, 6]]
[END] |
Python | Uncommon elements in Lists of List | https://www.geeksforgeeks.org/python-uncommon-elements-in-lists-of-list/?ref=leftbar-rightbar | # Python 3 code to demonstrate
# Uncommon elements in Lists of List
# using map() + set() + ^
# initializing lists
test_list1 = [[1, 2], [3, 4], [5, 6]]
test_list2 = [[3, 4], [5, 7], [1, 2]]
# printing both lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using map() + set() + ^
# Uncommon elements in Lists of List
res_set = set(map(tuple, test_list1)) ^ set(map(tuple, test_list2))
res_list = list(map(list, res_set))
# printing the uncommon
print("The uncommon of two lists is : " + str(res_list)) |
#Output : The original list 1 : [[1, 2], [3, 4], [5, 6]] | Python | Uncommon elements in Lists of List
# Python 3 code to demonstrate
# Uncommon elements in Lists of List
# using map() + set() + ^
# initializing lists
test_list1 = [[1, 2], [3, 4], [5, 6]]
test_list2 = [[3, 4], [5, 7], [1, 2]]
# printing both lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using map() + set() + ^
# Uncommon elements in Lists of List
res_set = set(map(tuple, test_list1)) ^ set(map(tuple, test_list2))
res_list = list(map(list, res_set))
# printing the uncommon
print("The uncommon of two lists is : " + str(res_list))
#Output : The original list 1 : [[1, 2], [3, 4], [5, 6]]
[END] |
Python | Uncommon elements in Lists of List | https://www.geeksforgeeks.org/python-uncommon-elements-in-lists-of-list/?ref=leftbar-rightbar | # initializing lists
test_list1 = [[1, 2], [3, 4], [5, 6]]
test_list2 = [[3, 4], [5, 7], [1, 2]]
# printing both lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
res_list = [x for x in test_list1 if x not in test_list2] + [
y for y in test_list2 if y not in test_list1
]
# printing the uncommon
print("The uncommon of two lists is : " + str(res_list))
# This code is contributed by Jyothi pinjala |
#Output : The original list 1 : [[1, 2], [3, 4], [5, 6]] | Python | Uncommon elements in Lists of List
# initializing lists
test_list1 = [[1, 2], [3, 4], [5, 6]]
test_list2 = [[3, 4], [5, 7], [1, 2]]
# printing both lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
res_list = [x for x in test_list1 if x not in test_list2] + [
y for y in test_list2 if y not in test_list1
]
# printing the uncommon
print("The uncommon of two lists is : " + str(res_list))
# This code is contributed by Jyothi pinjala
#Output : The original list 1 : [[1, 2], [3, 4], [5, 6]]
[END] |
Python program to select Random value from list of lists | https://www.geeksforgeeks.org/python-program-to-select-random-value-form-list-of-lists/ | # Python3 code to demonstrate working of
# Random Matrix Element
# Using chain.from_iterables() + random.choice()
from itertools import chain
import random
# Initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# Printing original list
print("The original list is : " + str(test_list))
# choice() for random number, from_iterables for flattening
res = random.choice(list(chain.from_iterable(test_list)))
# Printing result
print("Random number from Matrix : " + str(res)) | #Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
#Output : 7 | Python program to select Random value from list of lists
# Python3 code to demonstrate working of
# Random Matrix Element
# Using chain.from_iterables() + random.choice()
from itertools import chain
import random
# Initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# Printing original list
print("The original list is : " + str(test_list))
# choice() for random number, from_iterables for flattening
res = random.choice(list(chain.from_iterable(test_list)))
# Printing result
print("Random number from Matrix : " + str(res))
#Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
#Output : 7
[END] |
Python program to select Random value from list of lists | https://www.geeksforgeeks.org/python-program-to-select-random-value-form-list-of-lists/ | # Python3 code to demonstrate working of
# Random Matrix Element
# Using random.choice() [if row number given]
import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print("The original list is : " + str(test_list))
# initializing Row number
r_no = [0, 1, 2]
# choice() for random number, from_iterables for flattening
res = random.choice(test_list[random.choice(r_no)])
# printing result
print("Random number from Matrix Row : " + str(res)) | #Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
#Output : 7 | Python program to select Random value from list of lists
# Python3 code to demonstrate working of
# Random Matrix Element
# Using random.choice() [if row number given]
import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print("The original list is : " + str(test_list))
# initializing Row number
r_no = [0, 1, 2]
# choice() for random number, from_iterables for flattening
res = random.choice(test_list[random.choice(r_no)])
# printing result
print("Random number from Matrix Row : " + str(res))
#Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
#Output : 7
[END] |
Python program to select Random value from list of lists | https://www.geeksforgeeks.org/python-program-to-select-random-value-form-list-of-lists/ | import numpy as np
import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print("The original list is : " + str(test_list))
# initializing Row number
r_no = [0, 1, 2]
# Converting list to numpy array
arr = np.array(test_list)
# Generating random number from matrix
# using numpy random.choice() method
res = np.random.choice(arr[random.choice(r_no)])
# Printing result
print("Random number from Matrix Row : " + str(res)) | #Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
#Output : 7 | Python program to select Random value from list of lists
import numpy as np
import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print("The original list is : " + str(test_list))
# initializing Row number
r_no = [0, 1, 2]
# Converting list to numpy array
arr = np.array(test_list)
# Generating random number from matrix
# using numpy random.choice() method
res = np.random.choice(arr[random.choice(r_no)])
# Printing result
print("Random number from Matrix Row : " + str(res))
#Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
#Output : 7
[END] |
Python program to select Random value from list of lists | https://www.geeksforgeeks.org/python-program-to-select-random-value-form-list-of-lists/ | import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print("The original list is : " + str(test_list))
# generating random row index
row_index = random.randint(0, len(test_list) - 1)
# extracting the row corresponding to the random index using list comprehension
row = [test_list[row_index][i] for i in range(len(test_list[row_index]))]
# getting a sample of elements from the row using random.sample()
sample = random.sample(row, k=1)
# getting the randomly selected element from the sample
res = sample[0]
# printing result
print("Random number from Matrix Row : " + str(res)) | #Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
#Output : 7 | Python program to select Random value from list of lists
import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print("The original list is : " + str(test_list))
# generating random row index
row_index = random.randint(0, len(test_list) - 1)
# extracting the row corresponding to the random index using list comprehension
row = [test_list[row_index][i] for i in range(len(test_list[row_index]))]
# getting a sample of elements from the row using random.sample()
sample = random.sample(row, k=1)
# getting the randomly selected element from the sample
res = sample[0]
# printing result
print("Random number from Matrix Row : " + str(res))
#Input : test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
#Output : 7
[END] |
Python - Reverse Row sort in Lists of List | https://www.geeksforgeeks.org/python-reverse-row-sort-in-lists-of-list/ | # Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using loop
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using loop
for ele in test_list:
ele.sort(reverse=True)
# printing result
print("The reverse sorted Matrix is : " + str(test_list)) |
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]] | Python - Reverse Row sort in Lists of List
# Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using loop
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using loop
for ele in test_list:
ele.sort(reverse=True)
# printing result
print("The reverse sorted Matrix is : " + str(test_list))
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
[END] |
Python - Reverse Row sort in Lists of List | https://www.geeksforgeeks.org/python-reverse-row-sort-in-lists-of-list/ | # Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using list comprehension + sorted()
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using list comprehension + sorted()
res = [sorted(sub, reverse=True) for sub in test_list]
# printing result
print("The reverse sorted Matrix is : " + str(res)) |
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]] | Python - Reverse Row sort in Lists of List
# Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using list comprehension + sorted()
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using list comprehension + sorted()
res = [sorted(sub, reverse=True) for sub in test_list]
# printing result
print("The reverse sorted Matrix is : " + str(res))
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
[END] |
Python - Reverse Row sort in Lists of List | https://www.geeksforgeeks.org/python-reverse-row-sort-in-lists-of-list/ | # Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using map + sorted()
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using map + sorted()
res = list(map(lambda x: sorted(x, reverse=True), test_list))
# printing result
print("The reverse sorted Matrix is : " + str(res)) |
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]] | Python - Reverse Row sort in Lists of List
# Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using map + sorted()
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using map + sorted()
res = list(map(lambda x: sorted(x, reverse=True), test_list))
# printing result
print("The reverse sorted Matrix is : " + str(res))
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
[END] |
Python - Reverse Row sort in Lists of List | https://www.geeksforgeeks.org/python-reverse-row-sort-in-lists-of-list/ | # Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using loop
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using loop
res = []
for ele in test_list:
ele.sort()
res.append(ele[::-1])
# printing result
print("The reverse sorted Matrix is : " + str(res)) |
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]] | Python - Reverse Row sort in Lists of List
# Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using loop
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using loop
res = []
for ele in test_list:
ele.sort()
res.append(ele[::-1])
# printing result
print("The reverse sorted Matrix is : " + str(res))
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
[END] |
Python - Reverse Row sort in Lists of List | https://www.geeksforgeeks.org/python-reverse-row-sort-in-lists-of-list/ | def reverse_sort_matrix(matrix):
return list(map(lambda row: sorted(row, reverse=True), matrix))
matrix = [[4, 1, 6], [7, 8], [4, 10, 8]]
print(reverse_sort_matrix(matrix)) |
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]] | Python - Reverse Row sort in Lists of List
def reverse_sort_matrix(matrix):
return list(map(lambda row: sorted(row, reverse=True), matrix))
matrix = [[4, 1, 6], [7, 8], [4, 10, 8]]
print(reverse_sort_matrix(matrix))
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
[END] |
Python - Reverse Row sort in Lists of List | https://www.geeksforgeeks.org/python-reverse-row-sort-in-lists-of-list/ | # Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using the heapq module
import heapq
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using the heapq module
res = []
for sublist in test_list:
heapq.heapify(sublist)
res.append([heapq.heappop(sublist) for i in range(len(sublist))][::-1])
# printing result
print("The reverse sorted Matrix is : " + str(res)) |
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]] | Python - Reverse Row sort in Lists of List
# Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using the heapq module
import heapq
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Reverse Row sort in Lists of List
# using the heapq module
res = []
for sublist in test_list:
heapq.heapify(sublist)
res.append([heapq.heappop(sublist) for i in range(len(sublist))][::-1])
# printing result
print("The reverse sorted Matrix is : " + str(res))
#Output : The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
[END] |
Python - Pair elements with Rear element in Matrix Row | https://www.geeksforgeeks.org/python-pair-elements-with-rear-element-in-matrix-row/ | # Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using list comprehension
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using list comprehension
res = []
for sub in test_list:
res.append([[ele, sub[-1]] for ele in sub[:-1]])
# printing result
print("The list after pairing is : " + str(res)) |
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]] | Python - Pair elements with Rear element in Matrix Row
# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using list comprehension
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using list comprehension
res = []
for sub in test_list:
res.append([[ele, sub[-1]] for ele in sub[:-1]])
# printing result
print("The list after pairing is : " + str(res))
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
[END] |
Python - Pair elements with Rear element in Matrix Row | https://www.geeksforgeeks.org/python-pair-elements-with-rear-element-in-matrix-row/ | # Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using product() + loop
from itertools import product
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using product() + loop
res = []
for idx in test_list:
res.append(list(product(idx[:-1], [idx[-1]])))
# printing result
print("The list after pairing is : " + str(res)) |
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]] | Python - Pair elements with Rear element in Matrix Row
# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using product() + loop
from itertools import product
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using product() + loop
res = []
for idx in test_list:
res.append(list(product(idx[:-1], [idx[-1]])))
# printing result
print("The list after pairing is : " + str(res))
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
[END] |
Python - Pair elements with Rear element in Matrix Row | https://www.geeksforgeeks.org/python-pair-elements-with-rear-element-in-matrix-row/ | # Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using zip function
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using zip function
res = []
for sub in test_list:
res.append(list(zip(sub[:-1], [sub[-1]] * (len(sub) - 1))))
# printing result
print("The list after pairing is : " + str(res))
# this code contributed by tvsk |
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]] | Python - Pair elements with Rear element in Matrix Row
# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using zip function
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using zip function
res = []
for sub in test_list:
res.append(list(zip(sub[:-1], [sub[-1]] * (len(sub) - 1))))
# printing result
print("The list after pairing is : " + str(res))
# this code contributed by tvsk
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
[END] |
Python - Pair elements with Rear element in Matrix Row | https://www.geeksforgeeks.org/python-pair-elements-with-rear-element-in-matrix-row/ | # Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using map() and zip_longest()
from itertools import zip_longest
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using map() and zip_longest()
res = [
list(map(lambda x: (x[0], sub[-1]), zip_longest(sub[:-1], [], fillvalue=sub[-1])))
for sub in test_list
]
# printing result
print("The list after pairing is : " + str(res)) |
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]] | Python - Pair elements with Rear element in Matrix Row
# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using map() and zip_longest()
from itertools import zip_longest
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using map() and zip_longest()
res = [
list(map(lambda x: (x[0], sub[-1]), zip_longest(sub[:-1], [], fillvalue=sub[-1])))
for sub in test_list
]
# printing result
print("The list after pairing is : " + str(res))
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
[END] |
Python - Pair elements with Rear element in Matrix Row | https://www.geeksforgeeks.org/python-pair-elements-with-rear-element-in-matrix-row/ | # Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using nested loop
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using nested loop
res = []
for sub in test_list:
temp = []
for i in range(len(sub) - 1):
temp.append([sub[i], sub[-1]])
res.append(temp)
# printing result
print("The list after pairing is : " + str(res)) |
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]] | Python - Pair elements with Rear element in Matrix Row
# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using nested loop
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row
# using nested loop
res = []
for sub in test_list:
temp = []
for i in range(len(sub) - 1):
temp.append([sub[i], sub[-1]])
res.append(temp)
# printing result
print("The list after pairing is : " + str(res))
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
[END] |
Python - Pair elements with Rear element in Matrix Row | https://www.geeksforgeeks.org/python-pair-elements-with-rear-element-in-matrix-row/ | # Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using list comprehension with tuple packing and unpacking
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# Printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row using list comprehension with tuple packing and unpacking
res = [[(ele, sub[-1]) for ele in sub[:-1]] for sub in test_list]
# Printing result
print("The list after pairing is : " + str(res)) |
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]] | Python - Pair elements with Rear element in Matrix Row
# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using list comprehension with tuple packing and unpacking
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# Printing original list
print("The original list is : " + str(test_list))
# Pair elements with Rear element in Matrix Row using list comprehension with tuple packing and unpacking
res = [[(ele, sub[-1]) for ele in sub[:-1]] for sub in test_list]
# Printing result
print("The list after pairing is : " + str(res))
#Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
[END] |
Python Program to count unique values inside a list | https://www.geeksforgeeks.org/how-to-count-unique-values-inside-a-list/ | # taking an input list
input_list = [1, 2, 2, 5, 8, 4, 4, 8]
# taking an input list
l1 = []
# taking an counter
count = 0
# traversing the array
for item in input_list:
if item not in l1:
count += 1
l1.append(item)
# printing the output
print("No of unique items are:", count) |
#Output : No of unique items are: 5 | Python Program to count unique values inside a list
# taking an input list
input_list = [1, 2, 2, 5, 8, 4, 4, 8]
# taking an input list
l1 = []
# taking an counter
count = 0
# traversing the array
for item in input_list:
if item not in l1:
count += 1
l1.append(item)
# printing the output
print("No of unique items are:", count)
#Output : No of unique items are: 5
[END] |
Python Program to count unique values inside a list | https://www.geeksforgeeks.org/how-to-count-unique-values-inside-a-list/ | # importing Counter module
from collections import Counter
input_list = [1, 2, 2, 5, 8, 4, 4, 8]
# creating a list with the keys
items = Counter(input_list).keys()
print("No of unique items in the list are:", len(items)) |
#Output : No of unique items are: 5 | Python Program to count unique values inside a list
# importing Counter module
from collections import Counter
input_list = [1, 2, 2, 5, 8, 4, 4, 8]
# creating a list with the keys
items = Counter(input_list).keys()
print("No of unique items in the list are:", len(items))
#Output : No of unique items are: 5
[END] |
Python Program to count unique values inside a list | https://www.geeksforgeeks.org/how-to-count-unique-values-inside-a-list/ | input_list = [1, 2, 2, 5, 8, 4, 4, 8]
# converting our list to set
new_set = set(input_list)
print("No of unique items in the list are:", len(new_set)) |
#Output : No of unique items are: 5 | Python Program to count unique values inside a list
input_list = [1, 2, 2, 5, 8, 4, 4, 8]
# converting our list to set
new_set = set(input_list)
print("No of unique items in the list are:", len(new_set))
#Output : No of unique items are: 5
[END] |
Python Program to count unique values inside a list | https://www.geeksforgeeks.org/how-to-count-unique-values-inside-a-list/ | input_list = [1, 2, 2, 5, 8, 4, 4, 8]
# converting our list to filter list
new_set = [x for i, x in enumerate(input_list) if x not in input_list[:i]]
print("No of unique items in the list are:", len(new_set)) |
#Output : No of unique items are: 5 | Python Program to count unique values inside a list
input_list = [1, 2, 2, 5, 8, 4, 4, 8]
# converting our list to filter list
new_set = [x for i, x in enumerate(input_list) if x not in input_list[:i]]
print("No of unique items in the list are:", len(new_set))
#Output : No of unique items are: 5
[END] |
Python - List product excluding duplicates | https://www.geeksforgeeks.org/python-list-product-excluding-duplicates/ | # Python 3 code to demonstrate
# Duplication Removal List Product
# using naive methods
# getting Product
def prod(val):
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
# using naive method
# Duplication Removal List Product
res = []
for i in test_list:
if i not in res:
res.append(i)
res = prod(res)
# printing list after removal
print("Duplication removal list product : " + str(res)) |
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1] | Python - List product excluding duplicates
# Python 3 code to demonstrate
# Duplication Removal List Product
# using naive methods
# getting Product
def prod(val):
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
# using naive method
# Duplication Removal List Product
res = []
for i in test_list:
if i not in res:
res.append(i)
res = prod(res)
# printing list after removal
print("Duplication removal list product : " + str(res))
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
[END] |
Python - List product excluding duplicates | https://www.geeksforgeeks.org/python-list-product-excluding-duplicates/ | # Python 3 code to demonstrate
# Duplication Removal List Product
# using list comprehension
# getting Product
def prod(val):
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
# using list comprehension
# Duplication Removal List Product
res = []
[res.append(x) for x in test_list if x not in res]
res = prod(res)
# printing list after removal
print("Duplication removal list product : " + str(res)) |
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1] | Python - List product excluding duplicates
# Python 3 code to demonstrate
# Duplication Removal List Product
# using list comprehension
# getting Product
def prod(val):
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
# using list comprehension
# Duplication Removal List Product
res = []
[res.append(x) for x in test_list if x not in res]
res = prod(res)
# printing list after removal
print("Duplication removal list product : " + str(res))
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
[END] |
Python - List product excluding duplicates | https://www.geeksforgeeks.org/python-list-product-excluding-duplicates/ | import functools
functools.reduce(lambda x, y: x * y, set([1, 3, 5, 6, 3, 5, 6, 1]), 1) |
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1] | Python - List product excluding duplicates
import functools
functools.reduce(lambda x, y: x * y, set([1, 3, 5, 6, 3, 5, 6, 1]), 1)
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
[END] |
Python - List product excluding duplicates | https://www.geeksforgeeks.org/python-list-product-excluding-duplicates/ | # Python 3 code to demonstrate
# Duplication Removal List Product
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
# using naive method
# Duplication Removal List Product
x = list(set(test_list))
prod = 1
for i in x:
prod *= i
# printing list after removal
print("Duplication removal list product : " + str(prod)) |
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1] | Python - List product excluding duplicates
# Python 3 code to demonstrate
# Duplication Removal List Product
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
# using naive method
# Duplication Removal List Product
x = list(set(test_list))
prod = 1
for i in x:
prod *= i
# printing list after removal
print("Duplication removal list product : " + str(prod))
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
[END] |
Python - List product excluding duplicates | https://www.geeksforgeeks.org/python-list-product-excluding-duplicates/ | import math
def product(list):
s = set(list)
return math.prod(s)
l = [1, 3, 5, 6, 3, 5, 6, 1]
print(product(l)) |
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1] | Python - List product excluding duplicates
import math
def product(list):
s = set(list)
return math.prod(s)
l = [1, 3, 5, 6, 3, 5, 6, 1]
print(product(l))
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
[END] |
Python - List product excluding duplicates | https://www.geeksforgeeks.org/python-list-product-excluding-duplicates/ | import numpy as np
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
# converting list to numpy array and finding unique elements
unique_array = np.unique(np.array(test_list))
# finding product of unique elements
result = np.prod(unique_array)
# printing result
print("Duplication removal list product : " + str(result)) |
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1] | Python - List product excluding duplicates
import numpy as np
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
# converting list to numpy array and finding unique elements
unique_array = np.unique(np.array(test_list))
# finding product of unique elements
result = np.prod(unique_array)
# printing result
print("Duplication removal list product : " + str(result))
#Output : The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
[END] |
Python - Extract elements with Frequency greater than K | https://www.geeksforgeeks.org/python-extract-elements-with-frequency-greater-than-k/ | # Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
# Using count() + loop
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
res = []
for i in test_list:
# using count() to get count of elements
freq = test_list.count(i)
# checking if not already entered in results
if freq > K and i not in res:
res.append(i)
# printing results
print("The required elements : " + str(res)) |
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8] | Python - Extract elements with Frequency greater than K
# Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
# Using count() + loop
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
res = []
for i in test_list:
# using count() to get count of elements
freq = test_list.count(i)
# checking if not already entered in results
if freq > K and i not in res:
res.append(i)
# printing results
print("The required elements : " + str(res))
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
[END] |
Python - Extract elements with Frequency greater than K | https://www.geeksforgeeks.org/python-extract-elements-with-frequency-greater-than-k/ | # Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
# Using list comprehension + Counter()
from collections import Counter
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
# using list comprehension to bind result
res = [ele for ele, cnt in Counter(test_list).items() if cnt > K]
# printing results
print("The required elements : " + str(res)) |
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8] | Python - Extract elements with Frequency greater than K
# Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
# Using list comprehension + Counter()
from collections import Counter
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
# using list comprehension to bind result
res = [ele for ele, cnt in Counter(test_list).items() if cnt > K]
# printing results
print("The required elements : " + str(res))
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
[END] |
Python - Extract elements with Frequency greater than K | https://www.geeksforgeeks.org/python-extract-elements-with-frequency-greater-than-k/ | test_list = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6]
k = 2
unique_elems = []
freq_dict = {}
output = []
# printing string
print("The original list : " + str(test_list))
for i in test_list:
# Append in the unique element list
if i not in unique_elems:
unique_elems.append(i)
freq_dict[i] = 1
else:
# increment the counter if element is duplicate
freq_dict[i] += 1
# Add in the output list only once
if freq_dict[i] == k + 1:
output.append(i)
print("The required elements : ", str(output)) |
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8] | Python - Extract elements with Frequency greater than K
test_list = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6]
k = 2
unique_elems = []
freq_dict = {}
output = []
# printing string
print("The original list : " + str(test_list))
for i in test_list:
# Append in the unique element list
if i not in unique_elems:
unique_elems.append(i)
freq_dict[i] = 1
else:
# increment the counter if element is duplicate
freq_dict[i] += 1
# Add in the output list only once
if freq_dict[i] == k + 1:
output.append(i)
print("The required elements : ", str(output))
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
[END] |
Python - Extract elements with Frequency greater than K | https://www.geeksforgeeks.org/python-extract-elements-with-frequency-greater-than-k/ | # Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
import operator as op
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
unique_elements = set(test_list)
res = []
for i in unique_elements:
# using operatorcountOf() to get count of elements
if op.countOf(test_list, i) > K:
res.append(i)
# printing results
print("The required elements : " + str(res)) |
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8] | Python - Extract elements with Frequency greater than K
# Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
import operator as op
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
unique_elements = set(test_list)
res = []
for i in unique_elements:
# using operatorcountOf() to get count of elements
if op.countOf(test_list, i) > K:
res.append(i)
# printing results
print("The required elements : " + str(res))
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
[END] |
Python - Extract elements with Frequency greater than K | https://www.geeksforgeeks.org/python-extract-elements-with-frequency-greater-than-k/ | import numpy as np
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
K = 2
# use numpy unique to extract unique elements and their frequency
unique_elements, counts = np.unique(test_list, return_counts=True)
# extract elements with frequency greater than K
res = unique_elements[counts > K].tolist()
# printing results
print("The required elements : " + str(res))
# this code is contributed by Asif_Shaik |
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8] | Python - Extract elements with Frequency greater than K
import numpy as np
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
K = 2
# use numpy unique to extract unique elements and their frequency
unique_elements, counts = np.unique(test_list, return_counts=True)
# extract elements with frequency greater than K
res = unique_elements[counts > K].tolist()
# printing results
print("The required elements : " + str(res))
# this code is contributed by Asif_Shaik
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
[END] |
Python - Extract elements with Frequency greater than K | https://www.geeksforgeeks.org/python-extract-elements-with-frequency-greater-than-k/ | from collections import Counter
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
K = 2
freq_dict = Counter(test_list)
res = list(filter(lambda ele: freq_dict[ele] > K, freq_dict))
print("The required elements : " + str(res))
# This code is contributed By Vinay Pinjala. |
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8] | Python - Extract elements with Frequency greater than K
from collections import Counter
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
K = 2
freq_dict = Counter(test_list)
res = list(filter(lambda ele: freq_dict[ele] > K, freq_dict))
print("The required elements : " + str(res))
# This code is contributed By Vinay Pinjala.
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
[END] |
Python - Extract elements with Frequency greater than K | https://www.geeksforgeeks.org/python-extract-elements-with-frequency-greater-than-k/ | from collections import defaultdict
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
freq_dict = defaultdict(int)
for num in test_list:
freq_dict[num] += 1
K = 2
res = []
for num, freq in freq_dict.items():
if freq > K:
res.append(num)
# printing results
print("The required elements : " + str(res))
# This code is contributed by Jyothi Pinjala. |
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8] | Python - Extract elements with Frequency greater than K
from collections import defaultdict
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
freq_dict = defaultdict(int)
for num in test_list:
freq_dict[num] += 1
K = 2
res = []
for num, freq in freq_dict.items():
if freq > K:
res.append(num)
# printing results
print("The required elements : " + str(res))
# This code is contributed by Jyothi Pinjala.
#Output : The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
[END] |
Python - Test if List contains elements in Range | https://www.geeksforgeeks.org/python-test-if-list-contains-elements-in-range/ | # Python3 code to demonstrate
# Test if List contains elements in Range
# using loop
# Initializing loop
test_list = [4, 5, 6, 7, 3, 9]
# printing original list
print("The original list is : " + str(test_list))
# Initialization of range
i, j = 3, 10
# Test if List contains elements in Range
# using loop
res = True
for ele in test_list:
if ele < i or ele >= j:
res = False
break
# printing result
print("Does list contain all elements in range : " + str(res)) |
#Output : The original list is : [4, 5, 6, 7, 3, 9] | Python - Test if List contains elements in Range
# Python3 code to demonstrate
# Test if List contains elements in Range
# using loop
# Initializing loop
test_list = [4, 5, 6, 7, 3, 9]
# printing original list
print("The original list is : " + str(test_list))
# Initialization of range
i, j = 3, 10
# Test if List contains elements in Range
# using loop
res = True
for ele in test_list:
if ele < i or ele >= j:
res = False
break
# printing result
print("Does list contain all elements in range : " + str(res))
#Output : The original list is : [4, 5, 6, 7, 3, 9]
[END] |
Python - Test if List contains elements in Range | https://www.geeksforgeeks.org/python-test-if-list-contains-elements-in-range/ | # Python3 code to demonstrate
# Test if List contains elements in Range
# using all()
# Initializing loop
test_list = [4, 5, 6, 7, 3, 9]
# printing original list
print("The original list is : " + str(test_list))
# Initialization of range
i, j = 3, 10
# Test if List contains elements in Range
# using all()
res = all(ele >= i and ele < j for ele in test_list)
# printing result
print("Does list contain all elements in range : " + str(res)) |
#Output : The original list is : [4, 5, 6, 7, 3, 9] | Python - Test if List contains elements in Range
# Python3 code to demonstrate
# Test if List contains elements in Range
# using all()
# Initializing loop
test_list = [4, 5, 6, 7, 3, 9]
# printing original list
print("The original list is : " + str(test_list))
# Initialization of range
i, j = 3, 10
# Test if List contains elements in Range
# using all()
res = all(ele >= i and ele < j for ele in test_list)
# printing result
print("Does list contain all elements in range : " + str(res))
#Output : The original list is : [4, 5, 6, 7, 3, 9]
[END] |
Python - Test if List contains elements in Range | https://www.geeksforgeeks.org/python-test-if-list-contains-elements-in-range/ | # Python3 code to demonstrate
# Test if List contains elements in Range
# using List Comprehension and len()
# Initializing list
test_list = [4, 5, 6, 7, 3, 9]
# printing original list
print("The original list is : " + str(test_list))
# Initialization of range
i, j = 3, 10
# Test if List contains elements in Range
# using List Comprehension and len()
out_of_range = len([ele for ele in test_list if ele < i or ele >= j]) == 0
# printing result
print("Does list contain all elements in range : " + str(out_of_range)) |
#Output : The original list is : [4, 5, 6, 7, 3, 9] | Python - Test if List contains elements in Range
# Python3 code to demonstrate
# Test if List contains elements in Range
# using List Comprehension and len()
# Initializing list
test_list = [4, 5, 6, 7, 3, 9]
# printing original list
print("The original list is : " + str(test_list))
# Initialization of range
i, j = 3, 10
# Test if List contains elements in Range
# using List Comprehension and len()
out_of_range = len([ele for ele in test_list if ele < i or ele >= j]) == 0
# printing result
print("Does list contain all elements in range : " + str(out_of_range))
#Output : The original list is : [4, 5, 6, 7, 3, 9]
[END] |
Python - Test if List contains elements in Range | https://www.geeksforgeeks.org/python-test-if-list-contains-elements-in-range/ | # Python3 code to demonstrate
# Test if List contains elements in Range
# using any()
# Initializing list and range boundaries
test_list = [4, 5, 6, 7, 3, 9]
i, j = 3, 10
# Checking if any element in the list is within the range
res = any(i <= x < j for x in test_list)
# Printing the result
print("Does list contain any element in range: " + str(res)) |
#Output : The original list is : [4, 5, 6, 7, 3, 9] | Python - Test if List contains elements in Range
# Python3 code to demonstrate
# Test if List contains elements in Range
# using any()
# Initializing list and range boundaries
test_list = [4, 5, 6, 7, 3, 9]
i, j = 3, 10
# Checking if any element in the list is within the range
res = any(i <= x < j for x in test_list)
# Printing the result
print("Does list contain any element in range: " + str(res))
#Output : The original list is : [4, 5, 6, 7, 3, 9]
[END] |
Python program to check if the list contains three consecutive common numbers in Python | https://www.geeksforgeeks.org/python-program-to-check-if-the-list-contains-three-consecutive-common-numbers-in-python/ | # creating the array
arr = [4, 5, 5, 5, 3, 8]
# size of the list
size = len(arr)
# looping till length - 2
for i in range(size - 2):
# checking the conditions
if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]:
# printing the element as the
# conditions are satisfied
print(arr[i]) | #Input : [4, 5, 5, 5, 3, 8]
#Output : 5 | Python program to check if the list contains three consecutive common numbers in Python
# creating the array
arr = [4, 5, 5, 5, 3, 8]
# size of the list
size = len(arr)
# looping till length - 2
for i in range(size - 2):
# checking the conditions
if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]:
# printing the element as the
# conditions are satisfied
print(arr[i])
#Input : [4, 5, 5, 5, 3, 8]
#Output : 5
[END] |
Python program to check if the list contains three consecutive common numbers in Python | https://www.geeksforgeeks.org/python-program-to-check-if-the-list-contains-three-consecutive-common-numbers-in-python/ | # creating the array
arr = [1, 1, 1, 64, 23, 64, 22, 22, 22]
# size of the list
size = len(arr)
# looping till length - 2
for i in range(size - 2):
# checking the conditions
if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]:
# printing the element as the
# conditions are satisfied
print(arr[i]) | #Input : [4, 5, 5, 5, 3, 8]
#Output : 5 | Python program to check if the list contains three consecutive common numbers in Python
# creating the array
arr = [1, 1, 1, 64, 23, 64, 22, 22, 22]
# size of the list
size = len(arr)
# looping till length - 2
for i in range(size - 2):
# checking the conditions
if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]:
# printing the element as the
# conditions are satisfied
print(arr[i])
#Input : [4, 5, 5, 5, 3, 8]
#Output : 5
[END] |
Python program to check if the list contains three consecutive common numbers in Python | https://www.geeksforgeeks.org/python-program-to-check-if-the-list-contains-three-consecutive-common-numbers-in-python/ | # creating the array
arr = [1, 1, 1, 64, 23, 64, 22, 22, 22]
# size of the list
size = len(arr)
# looping till length - 2
for i in range(size - 2):
elements = set([arr[i], arr[i + 1], arr[i + 2]])
if len(elements) == 1:
print(arr[i]) | #Input : [4, 5, 5, 5, 3, 8]
#Output : 5 | Python program to check if the list contains three consecutive common numbers in Python
# creating the array
arr = [1, 1, 1, 64, 23, 64, 22, 22, 22]
# size of the list
size = len(arr)
# looping till length - 2
for i in range(size - 2):
elements = set([arr[i], arr[i + 1], arr[i + 2]])
if len(elements) == 1:
print(arr[i])
#Input : [4, 5, 5, 5, 3, 8]
#Output : 5
[END] |
Python program to check if the list contains three consecutive common numbers in Python | https://www.geeksforgeeks.org/python-program-to-check-if-the-list-contains-three-consecutive-common-numbers-in-python/ | import itertools
# creating the array
arr = [1, 1, 1, 64, 23, 64, 22, 22, 22]
triples = zip(arr, arr[1:], arr[2:])
print([x for x, y, z in itertools.islice(triples, len(arr) - 2) if x == y == z])
# This code is contributed by Jyothi pinjala | #Input : [4, 5, 5, 5, 3, 8]
#Output : 5 | Python program to check if the list contains three consecutive common numbers in Python
import itertools
# creating the array
arr = [1, 1, 1, 64, 23, 64, 22, 22, 22]
triples = zip(arr, arr[1:], arr[2:])
print([x for x, y, z in itertools.islice(triples, len(arr) - 2) if x == y == z])
# This code is contributed by Jyothi pinjala
#Input : [4, 5, 5, 5, 3, 8]
#Output : 5
[END] |
Python program to find the Strongest Neighbour | https://www.geeksforgeeks.org/python-program-to-find-the-strongest-neighbour/ | # define a function for finding
# the maximum for adjacent
# pairs in the array
def maximumAdjacent(arr1, n):
# array to store the max
# value between adjacent pairs
arr2 = []
# iterate from 1 to n - 1
for i in range(1, n):
# find max value between
# adjacent pairs gets
# stored in r
r = max(arr1[i], arr1[i - 1])
# add element
arr2.append(r)
# printing the elements
for ele in arr2:
print(ele, end=" ")
if __name__ == "__main__":
# size of the input array
n = 6
# input array
arr1 = [1, 2, 2, 3, 4, 5]
# function calling
maximumAdjacent(arr1, n) | Input: 1 2 2 3 4 5
Output: 2 2 3 4 5 | Python program to find the Strongest Neighbour
# define a function for finding
# the maximum for adjacent
# pairs in the array
def maximumAdjacent(arr1, n):
# array to store the max
# value between adjacent pairs
arr2 = []
# iterate from 1 to n - 1
for i in range(1, n):
# find max value between
# adjacent pairs gets
# stored in r
r = max(arr1[i], arr1[i - 1])
# add element
arr2.append(r)
# printing the elements
for ele in arr2:
print(ele, end=" ")
if __name__ == "__main__":
# size of the input array
n = 6
# input array
arr1 = [1, 2, 2, 3, 4, 5]
# function calling
maximumAdjacent(arr1, n)
Input: 1 2 2 3 4 5
Output: 2 2 3 4 5
[END] |
Python Program to print all Possible Combinations from the three Digits | https://www.geeksforgeeks.org/python-program-to-print-all-possible-combinations-from-the-three-digits/ | # Python program to print all
# the possible combinations
def comb(L):
for i in range(3):
for j in range(3):
for k in range(3):
# check if the indexes are not
# same
if i != j and j != k and i != k:
print(L[i], L[j], L[k])
# Driver Code
comb([1, 2, 3]) | Input: [1, 2, 3]
Output:
| Python Program to print all Possible Combinations from the three Digits
# Python program to print all
# the possible combinations
def comb(L):
for i in range(3):
for j in range(3):
for k in range(3):
# check if the indexes are not
# same
if i != j and j != k and i != k:
print(L[i], L[j], L[k])
# Driver Code
comb([1, 2, 3])
Input: [1, 2, 3]
Output:
[END] |
Python Program to print all Possible Combinations from the three Digits | https://www.geeksforgeeks.org/python-program-to-print-all-possible-combinations-from-the-three-digits/ | # Python program to print all
# the possible combinations
from itertools import permutations
# Get all combination of [1, 2, 3]
# of length 3
comb = permutations([1, 2, 3], 3)
for i in comb:
print(i) | Input: [1, 2, 3]
Output:
| Python Program to print all Possible Combinations from the three Digits
# Python program to print all
# the possible combinations
from itertools import permutations
# Get all combination of [1, 2, 3]
# of length 3
comb = permutations([1, 2, 3], 3)
for i in comb:
print(i)
Input: [1, 2, 3]
Output:
[END] |
Python program to find all the Combinations in the list with the given condition | https://www.geeksforgeeks.org/python-program-to-find-all-the-combinations-in-the-list-with-the-given-condition/ | from itertools import combinations
# initializing list
test_list = ["GFG", [5, 4], "is", ["best", "good", "better", "average"]]
idx = 0
temp = combinations(test_list, 2)
for i in list(temp):
idx = idx + 1
print("Combination", idx, ": ", i) |
#Output : Combination 1 : ('GFG', [5, 4]) | Python program to find all the Combinations in the list with the given condition
from itertools import combinations
# initializing list
test_list = ["GFG", [5, 4], "is", ["best", "good", "better", "average"]]
idx = 0
temp = combinations(test_list, 2)
for i in list(temp):
idx = idx + 1
print("Combination", idx, ": ", i)
#Output : Combination 1 : ('GFG', [5, 4])
[END] |
Python program to find all the Combinations in the list with the given condition | https://www.geeksforgeeks.org/python-program-to-find-all-the-combinations-in-the-list-with-the-given-condition/ | from itertools import combinations_with_replacement
# initializing list
test_list = ["GFG", [5, 4], "is", ["best", "good", "better", "average"]]
idx = 0
temp = combinations_with_replacement(test_list, 2)
for i in list(temp):
idx = idx + 1
print("Combination", idx, ": ", i) |
#Output : Combination 1 : ('GFG', [5, 4]) | Python program to find all the Combinations in the list with the given condition
from itertools import combinations_with_replacement
# initializing list
test_list = ["GFG", [5, 4], "is", ["best", "good", "better", "average"]]
idx = 0
temp = combinations_with_replacement(test_list, 2)
for i in list(temp):
idx = idx + 1
print("Combination", idx, ": ", i)
#Output : Combination 1 : ('GFG', [5, 4])
[END] |
Python program to find all the Combinations in the list with the given condition | https://www.geeksforgeeks.org/python-program-to-find-all-the-combinations-in-the-list-with-the-given-condition/ | def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indx = list(range(r))
yield tuple(pool[i] for i in indx)
while True:
for i in reversed(range(r)):
if indx[i] != i + n - r:
break
else:
return
indx[i] += 1
for j in range(i + 1, r):
indx[j] = indx[j - 1] + 1
yield tuple(pool[i] for i in indx)
x = [2, 3, 1, 6, 4, 7]
for i in combinations(x, 2):
print(i) |
#Output : Combination 1 : ('GFG', [5, 4]) | Python program to find all the Combinations in the list with the given condition
def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indx = list(range(r))
yield tuple(pool[i] for i in indx)
while True:
for i in reversed(range(r)):
if indx[i] != i + n - r:
break
else:
return
indx[i] += 1
for j in range(i + 1, r):
indx[j] = indx[j - 1] + 1
yield tuple(pool[i] for i in indx)
x = [2, 3, 1, 6, 4, 7]
for i in combinations(x, 2):
print(i)
#Output : Combination 1 : ('GFG', [5, 4])
[END] |
Python program to find all the Combinations in the list with the given condition | https://www.geeksforgeeks.org/python-program-to-find-all-the-combinations-in-the-list-with-the-given-condition/ | import copy
def combinations(target, data):
for i in range(len(data)):
new_lis = copy.copy(target)
new_data = copy.copy(data)
# print(new_lis, new_data)
new_lis.append(data[i])
new_data = data[i + 1 :]
print(new_lis)
combinations(new_lis, new_data)
target = []
data = [1, 2, 3, 4]
combinations(target, data) |
#Output : Combination 1 : ('GFG', [5, 4]) | Python program to find all the Combinations in the list with the given condition
import copy
def combinations(target, data):
for i in range(len(data)):
new_lis = copy.copy(target)
new_data = copy.copy(data)
# print(new_lis, new_data)
new_lis.append(data[i])
new_data = data[i + 1 :]
print(new_lis)
combinations(new_lis, new_data)
target = []
data = [1, 2, 3, 4]
combinations(target, data)
#Output : Combination 1 : ('GFG', [5, 4])
[END] |
Python program to get all unique combinations of two Lists | https://www.geeksforgeeks.org/python-program-to-get-all-unique-combinations-of-two-lists/ | # python program to demonstrate
# unique combination of two lists
# using zip() and permutation of itertools
# import itertools package
import itertools
from itertools import permutations
# initialize lists
list_1 = ["a", "b", "c", "d"]
list_2 = [1, 4, 9]
# create empty list to store the
# combinations
unique_combinations = []
# Getting all permutations of list_1
# with length of list_2
permut = itertools.permutations(list_1, len(list_2))
# zip() is called to pair each permutation
# and shorter list element into combination
for comb in permut:
zipped = zip(comb, list_2)
unique_combinations.append(list(zipped))
# printing unique_combination list
print(unique_combinations) |
#Output : List_1 = ["a","b"] | Python program to get all unique combinations of two Lists
# python program to demonstrate
# unique combination of two lists
# using zip() and permutation of itertools
# import itertools package
import itertools
from itertools import permutations
# initialize lists
list_1 = ["a", "b", "c", "d"]
list_2 = [1, 4, 9]
# create empty list to store the
# combinations
unique_combinations = []
# Getting all permutations of list_1
# with length of list_2
permut = itertools.permutations(list_1, len(list_2))
# zip() is called to pair each permutation
# and shorter list element into combination
for comb in permut:
zipped = zip(comb, list_2)
unique_combinations.append(list(zipped))
# printing unique_combination list
print(unique_combinations)
#Output : List_1 = ["a","b"]
[END] |
Python program to get all unique combinations of two Lists | https://www.geeksforgeeks.org/python-program-to-get-all-unique-combinations-of-two-lists/ | # python program to demonstrate
# unique combination of two lists
# using zip() and product() of itertools
# import itertools package
import itertools
from itertools import product
# initialize lists
list_1 = ["b", "c", "d"]
list_2 = [1, 4, 9]
# create empty list to store the combinations
unique_combinations = []
# Extract Combination Mapping in two lists
# using zip() + product()
unique_combinations = list(
list(zip(list_1, element)) for element in product(list_2, repeat=len(list_1))
)
# printing unique_combination list
print(unique_combinations) |
#Output : List_1 = ["a","b"] | Python program to get all unique combinations of two Lists
# python program to demonstrate
# unique combination of two lists
# using zip() and product() of itertools
# import itertools package
import itertools
from itertools import product
# initialize lists
list_1 = ["b", "c", "d"]
list_2 = [1, 4, 9]
# create empty list to store the combinations
unique_combinations = []
# Extract Combination Mapping in two lists
# using zip() + product()
unique_combinations = list(
list(zip(list_1, element)) for element in product(list_2, repeat=len(list_1))
)
# printing unique_combination list
print(unique_combinations)
#Output : List_1 = ["a","b"]
[END] |
Python program to get all unique combinations of two Lists | https://www.geeksforgeeks.org/python-program-to-get-all-unique-combinations-of-two-lists/ | list_1 = ["b", "c", "d"]
list_2 = [1, 4, 9]
unique_combinations = []
for i in range(len(list_1)):
for j in range(len(list_2)):
unique_combinations.append((list_1[i], list_2[j]))
print(unique_combinations) |
#Output : List_1 = ["a","b"] | Python program to get all unique combinations of two Lists
list_1 = ["b", "c", "d"]
list_2 = [1, 4, 9]
unique_combinations = []
for i in range(len(list_1)):
for j in range(len(list_2)):
unique_combinations.append((list_1[i], list_2[j]))
print(unique_combinations)
#Output : List_1 = ["a","b"]
[END] |
Python program to remove all the occurrences of an element from a list | https://www.geeksforgeeks.org/remove-all-the-occurrences-of-an-element-from-a-list-in-python/ | # Python 3 code to demonstrate
# the removal of all occurrences of a
# given item using list comprehension
def remove_items(test_list, item):
# using list comprehension to perform the task
res = [i for i in test_list if i != item]
return res
# driver code
if __name__ == "__main__":
# initializing the list
test_list = [1, 3, 4, 6, 5, 1]
# the item which is to be removed
item = 1
# printing the original list
print("The original list is : " + str(test_list))
# calling the function remove_items()
res = remove_items(test_list, item)
# printing result
print("The list after performing the remove operation is : " + str(res)) |
#Output : The original list is : [1, 3, 4, 6, 5, 1] | Python program to remove all the occurrences of an element from a list
# Python 3 code to demonstrate
# the removal of all occurrences of a
# given item using list comprehension
def remove_items(test_list, item):
# using list comprehension to perform the task
res = [i for i in test_list if i != item]
return res
# driver code
if __name__ == "__main__":
# initializing the list
test_list = [1, 3, 4, 6, 5, 1]
# the item which is to be removed
item = 1
# printing the original list
print("The original list is : " + str(test_list))
# calling the function remove_items()
res = remove_items(test_list, item)
# printing result
print("The list after performing the remove operation is : " + str(res))
#Output : The original list is : [1, 3, 4, 6, 5, 1]
[END] |
Python program to remove all the occurrences of an element from a list | https://www.geeksforgeeks.org/remove-all-the-occurrences-of-an-element-from-a-list-in-python/ | # Python 3 code to demonstrate
# the removal of all occurrences of
# a given item using filter() and __ne__
def remove_items(test_list, item):
# using filter() + __ne__ to perform the task
res = list(filter((item).__ne__, test_list))
return res
# driver code
if __name__ == "__main__":
# initializing the list
test_list = [1, 3, 4, 6, 5, 1]
# the item which is to be removed
item = 1
# printing the original list
print("The original list is : " + str(test_list))
# calling the function remove_items()
res = remove_items(test_list, item)
# printing result
print("The list after performing the remove operation is : " + str(res)) |
#Output : The original list is : [1, 3, 4, 6, 5, 1] | Python program to remove all the occurrences of an element from a list
# Python 3 code to demonstrate
# the removal of all occurrences of
# a given item using filter() and __ne__
def remove_items(test_list, item):
# using filter() + __ne__ to perform the task
res = list(filter((item).__ne__, test_list))
return res
# driver code
if __name__ == "__main__":
# initializing the list
test_list = [1, 3, 4, 6, 5, 1]
# the item which is to be removed
item = 1
# printing the original list
print("The original list is : " + str(test_list))
# calling the function remove_items()
res = remove_items(test_list, item)
# printing result
print("The list after performing the remove operation is : " + str(res))
#Output : The original list is : [1, 3, 4, 6, 5, 1]
[END] |
Python program to remove all the occurrences of an element from a list | https://www.geeksforgeeks.org/remove-all-the-occurrences-of-an-element-from-a-list-in-python/ | # Python 3 code to demonstrate
# the removal of all occurrences of
# a given item using remove()
def remove_items(test_list, item):
# remove the item for all its occurrences
c = test_list.count(item)
for i in range(c):
test_list.remove(item)
return test_list
# driver code
if __name__ == "__main__":
# initializing the list
test_list = [1, 3, 4, 6, 5, 1]
# the item which is to be removed
item = 1
# printing the original list
print("The original list is :" + str(test_list))
# calling the function remove_items()
res = remove_items(test_list, item)
# printing result
print("The list after performing the remove operation is :" + str(res)) |
#Output : The original list is : [1, 3, 4, 6, 5, 1] | Python program to remove all the occurrences of an element from a list
# Python 3 code to demonstrate
# the removal of all occurrences of
# a given item using remove()
def remove_items(test_list, item):
# remove the item for all its occurrences
c = test_list.count(item)
for i in range(c):
test_list.remove(item)
return test_list
# driver code
if __name__ == "__main__":
# initializing the list
test_list = [1, 3, 4, 6, 5, 1]
# the item which is to be removed
item = 1
# printing the original list
print("The original list is :" + str(test_list))
# calling the function remove_items()
res = remove_items(test_list, item)
# printing result
print("The list after performing the remove operation is :" + str(res))
#Output : The original list is : [1, 3, 4, 6, 5, 1]
[END] |
Python program to remove all the occurrences of an element from a list | https://www.geeksforgeeks.org/remove-all-the-occurrences-of-an-element-from-a-list-in-python/ | test_list = [1, 3, 4, 6, 5, 1]
ele = 1
x = [i for i in test_list if i != ele]
print(x) |
#Output : The original list is : [1, 3, 4, 6, 5, 1] | Python program to remove all the occurrences of an element from a list
test_list = [1, 3, 4, 6, 5, 1]
ele = 1
x = [i for i in test_list if i != ele]
print(x)
#Output : The original list is : [1, 3, 4, 6, 5, 1]
[END] |
Python program to remove all the occurrences of an element from a list | https://www.geeksforgeeks.org/remove-all-the-occurrences-of-an-element-from-a-list-in-python/ | # remove all occurrences of element in list
test_list = [1, 3, 4, 6, 5, 1]
ele = 1
a = list(map(str, test_list))
b = " ".join(a)
b = b.replace(str(ele), "")
b = b.split()
x = list(map(int, b))
print(x) |
#Output : The original list is : [1, 3, 4, 6, 5, 1] | Python program to remove all the occurrences of an element from a list
# remove all occurrences of element in list
test_list = [1, 3, 4, 6, 5, 1]
ele = 1
a = list(map(str, test_list))
b = " ".join(a)
b = b.replace(str(ele), "")
b = b.split()
x = list(map(int, b))
print(x)
#Output : The original list is : [1, 3, 4, 6, 5, 1]
[END] |
Python program to remove all the occurrences of an element from a list | https://www.geeksforgeeks.org/remove-all-the-occurrences-of-an-element-from-a-list-in-python/ | test_list = [1, 3, 4, 6, 5, 1]
ele = 1
x = [j for i, j in enumerate(test_list) if j != ele]
print(x) |
#Output : The original list is : [1, 3, 4, 6, 5, 1] | Python program to remove all the occurrences of an element from a list
test_list = [1, 3, 4, 6, 5, 1]
ele = 1
x = [j for i, j in enumerate(test_list) if j != ele]
print(x)
#Output : The original list is : [1, 3, 4, 6, 5, 1]
[END] |
Python - Remove Consecutive K element records | https://www.geeksforgeeks.org/python-remove-consecutive-k-element-records/ | # Python3 code to demonstrate working of
# Remove Consecutive K element records
# Using zip() + list comprehension
# initializing list
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# Remove Consecutive K element records
# Using zip() + list comprehension
res = [idx for idx in test_list if (K, K) not in zip(idx, idx[1:])]
# printing result
print("The records after removal : " + str(res)) |
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)] | Python - Remove Consecutive K element records
# Python3 code to demonstrate working of
# Remove Consecutive K element records
# Using zip() + list comprehension
# initializing list
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# Remove Consecutive K element records
# Using zip() + list comprehension
res = [idx for idx in test_list if (K, K) not in zip(idx, idx[1:])]
# printing result
print("The records after removal : " + str(res))
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
[END] |
Python - Remove Consecutive K element records | https://www.geeksforgeeks.org/python-remove-consecutive-k-element-records/ | # Python3 code to demonstrate working of
# Remove Consecutive K element records
# Using any() + list comprehension
# initializing list
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# Remove Consecutive K element records
# Using any() + list comprehension
res = [
idx
for idx in test_list
if not any(idx[j] == K and idx[j + 1] == K for j in range(len(idx) - 1))
]
# printing result
print("The records after removal : " + str(res)) |
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)] | Python - Remove Consecutive K element records
# Python3 code to demonstrate working of
# Remove Consecutive K element records
# Using any() + list comprehension
# initializing list
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# Remove Consecutive K element records
# Using any() + list comprehension
res = [
idx
for idx in test_list
if not any(idx[j] == K and idx[j + 1] == K for j in range(len(idx) - 1))
]
# printing result
print("The records after removal : " + str(res))
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
[END] |
Python - Remove Consecutive K element records | https://www.geeksforgeeks.org/python-remove-consecutive-k-element-records/ | test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
temp_list = []
for item in test_list:
skip = False
for i in range(len(item) - 1):
if item[i] == K and item[i + 1] == K:
skip = True
break
if not skip:
temp_list.append(item)
res = temp_list
print("The records after removal : ", res) |
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)] | Python - Remove Consecutive K element records
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
temp_list = []
for item in test_list:
skip = False
for i in range(len(item) - 1):
if item[i] == K and item[i + 1] == K:
skip = True
break
if not skip:
temp_list.append(item)
res = temp_list
print("The records after removal : ", res)
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
[END] |
Python - Remove Consecutive K element records | https://www.geeksforgeeks.org/python-remove-consecutive-k-element-records/ | test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
res = list(filter(lambda x: not any(i == j == K for i, j in zip(x, x[1:])), test_list))
print("The records after removal : ", res) |
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)] | Python - Remove Consecutive K element records
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
res = list(filter(lambda x: not any(i == j == K for i, j in zip(x, x[1:])), test_list))
print("The records after removal : ", res)
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
[END] |
Python - Remove Consecutive K element records | https://www.geeksforgeeks.org/python-remove-consecutive-k-element-records/ | import itertools
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
res = list(
itertools.filterfalse(
lambda item: any(
item[i] == K and item[i + 1] == K for i in range(len(item) - 1)
),
test_list,
)
)
print("The records after removal : ", res) |
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)] | Python - Remove Consecutive K element records
import itertools
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
res = list(
itertools.filterfalse(
lambda item: any(
item[i] == K and item[i + 1] == K for i in range(len(item) - 1)
),
test_list,
)
)
print("The records after removal : ", res)
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
[END] |
Python - Remove Consecutive K element records | https://www.geeksforgeeks.org/python-remove-consecutive-k-element-records/ | import numpy as np
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
# printing original list
print("The original list is : " + str(test_list))
# Convert list of tuples to 2D NumPy array
arr = np.array(test_list)
# Check if consecutive elements in each row are equal to K
mask = np.logical_not(np.any((arr[:, :-1] == K) & (arr[:, 1:] == K), axis=1))
# Filter the rows based on the mask
res = arr[mask]
print("The records after removal : ", res)
# This code is contributed by Vinay Pinjala |
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)] | Python - Remove Consecutive K element records
import numpy as np
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
# printing original list
print("The original list is : " + str(test_list))
# Convert list of tuples to 2D NumPy array
arr = np.array(test_list)
# Check if consecutive elements in each row are equal to K
mask = np.logical_not(np.any((arr[:, :-1] == K) & (arr[:, 1:] == K), axis=1))
# Filter the rows based on the mask
res = arr[mask]
print("The records after removal : ", res)
# This code is contributed by Vinay Pinjala
#Output : The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
[END] |
Python - Replace index elements with elements in Other List | https://www.geeksforgeeks.org/python-replace-index-elements-with-elements-in-other-list/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Replace index elements with elements in Other List
# using list comprehension
# Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using list comprehension
res = [test_list1[idx] for idx in test_list2]
# printing result
print("The lists after index elements replacements is : " + str(res)) |
#Output : The original list 1 is : ['Gfg', 'is', 'best'] | Python - Replace index elements with elements in Other List
# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using list comprehension
# Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using list comprehension
res = [test_list1[idx] for idx in test_list2]
# printing result
print("The lists after index elements replacements is : " + str(res))
#Output : The original list 1 is : ['Gfg', 'is', 'best']
[END] |
Python - Replace index elements with elements in Other List | https://www.geeksforgeeks.org/python-replace-index-elements-with-elements-in-other-list/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Replace index elements with elements in Other List
# using map() + lambda
# Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using map() + lambda
res = list(map(lambda idx: test_list1[idx], test_list2))
# printing result
print("The lists after index elements replacements is : " + str(res)) |
#Output : The original list 1 is : ['Gfg', 'is', 'best'] | Python - Replace index elements with elements in Other List
# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using map() + lambda
# Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using map() + lambda
res = list(map(lambda idx: test_list1[idx], test_list2))
# printing result
print("The lists after index elements replacements is : " + str(res))
#Output : The original list 1 is : ['Gfg', 'is', 'best']
[END] |
Python - Replace index elements with elements in Other List | https://www.geeksforgeeks.org/python-replace-index-elements-with-elements-in-other-list/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Replace index elements with elements in Other List
# using numpy.take()
# import numpy
import numpy as np
# Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using numpy.take()
res = np.take(test_list1, test_list2)
# printing result
print("The lists after index elements replacements is : " + str(res)) |
#Output : The original list 1 is : ['Gfg', 'is', 'best'] | Python - Replace index elements with elements in Other List
# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using numpy.take()
# import numpy
import numpy as np
# Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using numpy.take()
res = np.take(test_list1, test_list2)
# printing result
print("The lists after index elements replacements is : " + str(res))
#Output : The original list 1 is : ['Gfg', 'is', 'best']
[END] |
Python - Replace index elements with elements in Other List | https://www.geeksforgeeks.org/python-replace-index-elements-with-elements-in-other-list/?ref=leftbar-rightbar | # Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Create a dictionary to map indices to elements in test_list1
index_map = {index: element for index, element in enumerate(test_list1)}
# Replace index elements with elements in Other List using a for loop
res = [index_map[idx] for idx in test_list2]
# printing result
print("The lists after index elements replacements is : " + str(res))
# This code is contributed by Vinay Pinjala. |
#Output : The original list 1 is : ['Gfg', 'is', 'best'] | Python - Replace index elements with elements in Other List
# Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Create a dictionary to map indices to elements in test_list1
index_map = {index: element for index, element in enumerate(test_list1)}
# Replace index elements with elements in Other List using a for loop
res = [index_map[idx] for idx in test_list2]
# printing result
print("The lists after index elements replacements is : " + str(res))
# This code is contributed by Vinay Pinjala.
#Output : The original list 1 is : ['Gfg', 'is', 'best']
[END] |
Python - Replace index elements with elements in Other List | https://www.geeksforgeeks.org/python-replace-index-elements-with-elements-in-other-list/?ref=leftbar-rightbar | import pandas as pd
# Initializing the two lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# Creating a dataframe with one column ('a') containing the values from test_list1
df = pd.DataFrame({"a": test_list1})
# Extracting the values from test_list1 corresponding to the indices in test_list2
# by using the loc[] function of the dataframe and converting the result to a list
res = df.loc[test_list2, "a"].tolist()
# Printing the resulting list
print("The lists after index elements replacements is : " + str(res)) |
#Output : The original list 1 is : ['Gfg', 'is', 'best'] | Python - Replace index elements with elements in Other List
import pandas as pd
# Initializing the two lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# Creating a dataframe with one column ('a') containing the values from test_list1
df = pd.DataFrame({"a": test_list1})
# Extracting the values from test_list1 corresponding to the indices in test_list2
# by using the loc[] function of the dataframe and converting the result to a list
res = df.loc[test_list2, "a"].tolist()
# Printing the resulting list
print("The lists after index elements replacements is : " + str(res))
#Output : The original list 1 is : ['Gfg', 'is', 'best']
[END] |
Python - Replace index elements with elements in Other List | https://www.geeksforgeeks.org/python-replace-index-elements-with-elements-in-other-list/?ref=leftbar-rightbar | # Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Using zip() function
res = [test_list1[i] for i in test_list2]
# printing result
print("The lists after index elements replacements is : " + str(res))
# This code is contributed by Vinay Pinjala. |
#Output : The original list 1 is : ['Gfg', 'is', 'best'] | Python - Replace index elements with elements in Other List
# Initializing lists
test_list1 = ["Gfg", "is", "best"]
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Using zip() function
res = [test_list1[i] for i in test_list2]
# printing result
print("The lists after index elements replacements is : " + str(res))
# This code is contributed by Vinay Pinjala.
#Output : The original list 1 is : ['Gfg', 'is', 'best']
[END] |
Python Program to Retain records with N occurrences of K | https://www.geeksforgeeks.org/python-retain-records-with-n-occurrences-of-k/ | # Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using count() + list comprehension
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using count() + list comprehension
res = [ele for ele in test_list if ele.count(K) == N]
# printing result
print("Filtered tuples : " + str(res)) |
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)] | Python Program to Retain records with N occurrences of K
# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using count() + list comprehension
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using count() + list comprehension
res = [ele for ele in test_list if ele.count(K) == N]
# printing result
print("Filtered tuples : " + str(res))
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
[END] |
Python Program to Retain records with N occurrences of K | https://www.geeksforgeeks.org/python-retain-records-with-n-occurrences-of-k/ | # Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using list comprehension + sum()
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using list comprehension + sum()
res = [ele for ele in test_list if sum(cnt == K for cnt in ele) == N]
# printing result
print("Filtered tuples : " + str(res)) |
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)] | Python Program to Retain records with N occurrences of K
# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using list comprehension + sum()
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using list comprehension + sum()
res = [ele for ele in test_list if sum(cnt == K for cnt in ele) == N]
# printing result
print("Filtered tuples : " + str(res))
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
[END] |
Python Program to Retain records with N occurrences of K | https://www.geeksforgeeks.org/python-retain-records-with-n-occurrences-of-k/ | # Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using count() + Recursive function
def retain_records(lst, k, n):
# Base case: if the list is empty, return an empty list
if not lst:
return []
# Recursive case: if the first tuple has N occurrences of K,
# append it to the result list and call the function recursively
# with the rest of the list.
else:
if lst[0].count(k) == n:
return [lst[0]] + retain_records(lst[1:], k, n)
else:
return retain_records(lst[1:], k, n)
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using count() +Recursive function
res = retain_records(test_list, K, N)
# printing result
print("Filtered tuples : " + str(res))
# this code contributed by tvsk |
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)] | Python Program to Retain records with N occurrences of K
# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using count() + Recursive function
def retain_records(lst, k, n):
# Base case: if the list is empty, return an empty list
if not lst:
return []
# Recursive case: if the first tuple has N occurrences of K,
# append it to the result list and call the function recursively
# with the rest of the list.
else:
if lst[0].count(k) == n:
return [lst[0]] + retain_records(lst[1:], k, n)
else:
return retain_records(lst[1:], k, n)
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using count() +Recursive function
res = retain_records(test_list, K, N)
# printing result
print("Filtered tuples : " + str(res))
# this code contributed by tvsk
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
[END] |
Python Program to Retain records with N occurrences of K | https://www.geeksforgeeks.org/python-retain-records-with-n-occurrences-of-k/ | # Python3 code to demonstrate working of
# Retain records with N occurrences of K
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
res = []
import operator
for i in test_list:
if operator.countOf(i, K) == N:
res.append(i)
# printing result
print("Filtered tuples : " + str(res)) |
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)] | Python Program to Retain records with N occurrences of K
# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
res = []
import operator
for i in test_list:
if operator.countOf(i, K) == N:
res.append(i)
# printing result
print("Filtered tuples : " + str(res))
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
[END] |
Python Program to Retain records with N occurrences of K | https://www.geeksforgeeks.org/python-retain-records-with-n-occurrences-of-k/ | # Define a list of tuples
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# Define the value of K and N
K = 4
N = 3
# printing original list
print("The original list is : " + str(test_list))
# Use the filter() function to create a new list of tuples that only contain tuples that have exactly N occurrences of K
# The lambda function checks how many times K occurs in each tuple x, and returns True if the count is equal to N
# The filter() function returns an iterator, so we convert it to a list with list()
res = list(filter(lambda x: x.count(K) == N, test_list))
# Print out the filtered tuples
print("Filtered tuples : " + str(res))
# This code is contributed by Jyothi pinjala. |
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)] | Python Program to Retain records with N occurrences of K
# Define a list of tuples
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# Define the value of K and N
K = 4
N = 3
# printing original list
print("The original list is : " + str(test_list))
# Use the filter() function to create a new list of tuples that only contain tuples that have exactly N occurrences of K
# The lambda function checks how many times K occurs in each tuple x, and returns True if the count is equal to N
# The filter() function returns an iterator, so we convert it to a list with list()
res = list(filter(lambda x: x.count(K) == N, test_list))
# Print out the filtered tuples
print("Filtered tuples : " + str(res))
# This code is contributed by Jyothi pinjala.
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
[END] |
Python Program to Retain records with N occurrences of K | https://www.geeksforgeeks.org/python-retain-records-with-n-occurrences-of-k/ | # initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# initializing K
K = 4
# initializing N
N = 3
# Using for loop
res = []
for tup in test_list:
if tup.count(K) == N:
res.append(tup)
# printing result
print("Filtered tuples : " + str(res))
# This code is contributed by Vinay Pinjala. |
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)] | Python Program to Retain records with N occurrences of K
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# initializing K
K = 4
# initializing N
N = 3
# Using for loop
res = []
for tup in test_list:
if tup.count(K) == N:
res.append(tup)
# printing result
print("Filtered tuples : " + str(res))
# This code is contributed by Vinay Pinjala.
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
[END] |
Python Program to Retain records with N occurrences of K | https://www.geeksforgeeks.org/python-retain-records-with-n-occurrences-of-k/ | import functools
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# initializing K
K = 4
# initializing N
N = 3
# define the function to count the number of times k occurs in a tuple
def count_k_in_tuple(k, tuple_t):
count = tuple_t.count(k)
if count == N:
return True
else:
return False
# create a partial function using the count_k_in_tuple function and the value of K
filter_func = functools.partial(count_k_in_tuple, K)
# use the filter function to filter the tuples based on the given conditions
filtered_tuples = filter(filter_func, test_list)
# convert the filtered tuples into a list
res = list(filtered_tuples)
# print the result
print("Filtered tuples : " + str(res)) |
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)] | Python Program to Retain records with N occurrences of K
import functools
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# initializing K
K = 4
# initializing N
N = 3
# define the function to count the number of times k occurs in a tuple
def count_k_in_tuple(k, tuple_t):
count = tuple_t.count(k)
if count == N:
return True
else:
return False
# create a partial function using the count_k_in_tuple function and the value of K
filter_func = functools.partial(count_k_in_tuple, K)
# use the filter function to filter the tuples based on the given conditions
filtered_tuples = filter(filter_func, test_list)
# convert the filtered tuples into a list
res = list(filtered_tuples)
# print the result
print("Filtered tuples : " + str(res))
#Output : The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
[END] |
Python - Swap elements in String List | https://www.geeksforgeeks.org/python-swap-elements-in-string-list/ | # Python3 code to demonstrate
# Swap elements in String list
# using replace() + list comprehension
# Initializing list
test_list = ["Gfg", "is", "best", "for", "Geeks"]
# printing original lists
print("The original list is : " + str(test_list))
# Swap elements in String list
# using replace() + list comprehension
res = [sub.replace("G", "-").replace("e", "G").replace("-", "e") for sub in test_list]
# printing result
print("List after performing character swaps : " + str(res)) |
#Output : The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks'] | Python - Swap elements in String List
# Python3 code to demonstrate
# Swap elements in String list
# using replace() + list comprehension
# Initializing list
test_list = ["Gfg", "is", "best", "for", "Geeks"]
# printing original lists
print("The original list is : " + str(test_list))
# Swap elements in String list
# using replace() + list comprehension
res = [sub.replace("G", "-").replace("e", "G").replace("-", "e") for sub in test_list]
# printing result
print("List after performing character swaps : " + str(res))
#Output : The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks']
[END] |
Python - Swap elements in String List | https://www.geeksforgeeks.org/python-swap-elements-in-string-list/ | # Python3 code to demonstrate
# Swap elements in String list
# using replace() + join() + split()
# Initializing list
test_list = ["Gfg", "is", "best", "for", "Geeks"]
# printing original lists
print("The original list is : " + str(test_list))
# Swap elements in String list
# using replace() + join() + split()
res = ", ".join(test_list)
res = res.replace("G", "_").replace("e", "G").replace("_", "e").split(", ")
# printing result
print("List after performing character swaps : " + str(res)) |
#Output : The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks'] | Python - Swap elements in String List
# Python3 code to demonstrate
# Swap elements in String list
# using replace() + join() + split()
# Initializing list
test_list = ["Gfg", "is", "best", "for", "Geeks"]
# printing original lists
print("The original list is : " + str(test_list))
# Swap elements in String list
# using replace() + join() + split()
res = ", ".join(test_list)
res = res.replace("G", "_").replace("e", "G").replace("_", "e").split(", ")
# printing result
print("List after performing character swaps : " + str(res))
#Output : The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks']
[END] |
Python - Swap elements in String List | https://www.geeksforgeeks.org/python-swap-elements-in-string-list/ | # Python3 code to demonstrate
# Swap elements in String list
# using regex
# Initializing list
import re
test_list = ["Gfg", "is", "best", "for", "Geeks"]
# printing original lists
print("The original list is : " + str(test_list))
# Swap elements in String list
# using regex
res = [re.sub("-", "e", re.sub("e", "G", re.sub("G", "-", sub))) for sub in test_list]
# printing result
print("List after performing character swaps : " + str(res)) |
#Output : The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks'] | Python - Swap elements in String List
# Python3 code to demonstrate
# Swap elements in String list
# using regex
# Initializing list
import re
test_list = ["Gfg", "is", "best", "for", "Geeks"]
# printing original lists
print("The original list is : " + str(test_list))
# Swap elements in String list
# using regex
res = [re.sub("-", "e", re.sub("e", "G", re.sub("G", "-", sub))) for sub in test_list]
# printing result
print("List after performing character swaps : " + str(res))
#Output : The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks']
[END] |
Python program to reverse All String in String List | https://www.geeksforgeeks.org/python-reverse-all-strings-in-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Reverse All Strings in String List
# using list comprehension
# initializing list
test_list = ["geeks", "for", "geeks", "is", "best"]
# printing original list
print("The original list is : " + str(test_list))
# using list comprehension
# Reverse All Strings in String List
res = [i[::-1] for i in test_list]
# printing result
print("The reversed string list is : " + str(res)) |
#Output : The original list is : ['geeks', 'for', 'geeks', 'is', 'best'] | Python program to reverse All String in String List
# Python3 code to demonstrate
# Reverse All Strings in String List
# using list comprehension
# initializing list
test_list = ["geeks", "for", "geeks", "is", "best"]
# printing original list
print("The original list is : " + str(test_list))
# using list comprehension
# Reverse All Strings in String List
res = [i[::-1] for i in test_list]
# printing result
print("The reversed string list is : " + str(res))
#Output : The original list is : ['geeks', 'for', 'geeks', 'is', 'best']
[END] |
Python program to reverse All String in String List | https://www.geeksforgeeks.org/python-reverse-all-strings-in-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Reverse All Strings in String List
# using map()
# initializing list
test_list = ["geeks", "for", "geeks", "is", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Reverse All Strings in String List
# using map()
reverse = lambda i: i[::-1]
res = list(map(reverse, test_list))
# printing result
print("The reversed string list is : " + str(res)) |
#Output : The original list is : ['geeks', 'for', 'geeks', 'is', 'best'] | Python program to reverse All String in String List
# Python3 code to demonstrate
# Reverse All Strings in String List
# using map()
# initializing list
test_list = ["geeks", "for", "geeks", "is", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Reverse All Strings in String List
# using map()
reverse = lambda i: i[::-1]
res = list(map(reverse, test_list))
# printing result
print("The reversed string list is : " + str(res))
#Output : The original list is : ['geeks', 'for', 'geeks', 'is', 'best']
[END] |
Python program to reverse All String in String List | https://www.geeksforgeeks.org/python-reverse-all-strings-in-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Reverse All Strings in String List
# using join() and reversed()
# initializing list
test_list = ["geeks", "for", "geeks", "is", "best"]
# printing original list
print("The original list is : " + str(test_list))
# using join() and reversed()
res = ["".join(reversed(i)) for i in test_list]
# printing result
print("The reversed string list is : " + str(res)) |
#Output : The original list is : ['geeks', 'for', 'geeks', 'is', 'best'] | Python program to reverse All String in String List
# Python3 code to demonstrate
# Reverse All Strings in String List
# using join() and reversed()
# initializing list
test_list = ["geeks", "for", "geeks", "is", "best"]
# printing original list
print("The original list is : " + str(test_list))
# using join() and reversed()
res = ["".join(reversed(i)) for i in test_list]
# printing result
print("The reversed string list is : " + str(res))
#Output : The original list is : ['geeks', 'for', 'geeks', 'is', 'best']
[END] |
Python program to reverse All String in String List | https://www.geeksforgeeks.org/python-reverse-all-strings-in-string-list/?ref=leftbar-rightbar | # define the original list of strings
test_list = ["geeks", "for", "geeks", "is", "best"]
# create an empty list to store the reversed strings
res = []
# iterate over each string in the original list
for string in test_list:
# use slicing to reverse the string and append it to the result list
res.append(string[::-1])
# print the list of reversed strings
print(res) |
#Output : The original list is : ['geeks', 'for', 'geeks', 'is', 'best'] | Python program to reverse All String in String List
# define the original list of strings
test_list = ["geeks", "for", "geeks", "is", "best"]
# create an empty list to store the reversed strings
res = []
# iterate over each string in the original list
for string in test_list:
# use slicing to reverse the string and append it to the result list
res.append(string[::-1])
# print the list of reversed strings
print(res)
#Output : The original list is : ['geeks', 'for', 'geeks', 'is', 'best']
[END] |
Python program to find the character position of Kth word from a list of strings | https://www.geeksforgeeks.org/python-program-to-find-the-character-position-of-kth-word-from-a-list-of-strings/ | # Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using enumerate() + list comprehension
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
# getting index of word
res = res[K]
# printing result
print("Index of character at Kth position word : " + str(res)) |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python program to find the character position of Kth word from a list of strings
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using enumerate() + list comprehension
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
# getting index of word
res = res[K]
# printing result
print("Index of character at Kth position word : " + str(res))
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |
Python program to find the character position of Kth word from a list of strings | https://www.geeksforgeeks.org/python-program-to-find-the-character-position-of-kth-word-from-a-list-of-strings/ | # Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using next() + zip() + count()
from itertools import count
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# count() for getting count
# pairing using zip()
cnt = count()
res = next(j for sub in test_list for j, idx in zip(range(len(sub)), cnt) if idx == K)
# printing result
print("Index of character at Kth position word : " + str(res)) |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python program to find the character position of Kth word from a list of strings
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using next() + zip() + count()
from itertools import count
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# count() for getting count
# pairing using zip()
cnt = count()
res = next(j for sub in test_list for j, idx in zip(range(len(sub)), cnt) if idx == K)
# printing result
print("Index of character at Kth position word : " + str(res))
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |
Python program to find the character position of Kth word from a list of strings | https://www.geeksforgeeks.org/python-program-to-find-the-character-position-of-kth-word-from-a-list-of-strings/ | # Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using nested loop
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# initializing index counter
idx = 0
# iterating over each word in the list
for word in test_list:
# if the kth position is in the current word
if idx + len(word) > K:
# printing result
print("Index of character at Kth position word : " + str(K - idx))
break
# if the kth position is not in the current word
else:
idx += len(word)
# if the kth position is beyond the end of the list
else:
print("K is beyond the end of the list") |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python program to find the character position of Kth word from a list of strings
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using nested loop
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# initializing index counter
idx = 0
# iterating over each word in the list
for word in test_list:
# if the kth position is in the current word
if idx + len(word) > K:
# printing result
print("Index of character at Kth position word : " + str(K - idx))
break
# if the kth position is not in the current word
else:
idx += len(word)
# if the kth position is beyond the end of the list
else:
print("K is beyond the end of the list")
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |
Python - Extract words starting with K in String List | https://www.geeksforgeeks.org/python-extract-words-starting-with-k-in-string-list/ | # Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using loop + split()
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
for sub in test_list:
# splitting phrases
temp = sub.split()
for ele in temp:
# checking for matching elements
if ele[0].lower() == K.lower():
res.append(ele)
# printing result
print("The filtered elements : " + str(res)) |
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G'] | Python - Extract words starting with K in String List
# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using loop + split()
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
for sub in test_list:
# splitting phrases
temp = sub.split()
for ele in temp:
# checking for matching elements
if ele[0].lower() == K.lower():
res.append(ele)
# printing result
print("The filtered elements : " + str(res))
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
[END] |
Python - Extract words starting with K in String List | https://www.geeksforgeeks.org/python-extract-words-starting-with-k-in-string-list/ | # Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using list comprehension + split()
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = [ele for temp in test_list for ele in temp.split() if ele[0].lower() == K.lower()]
# printing result
print("The filtered elements : " + str(res)) |
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G'] | Python - Extract words starting with K in String List
# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using list comprehension + split()
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = [ele for temp in test_list for ele in temp.split() if ele[0].lower() == K.lower()]
# printing result
print("The filtered elements : " + str(res))
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
[END] |
Python - Extract words starting with K in String List | https://www.geeksforgeeks.org/python-extract-words-starting-with-k-in-string-list/ | # Python3 code to demonstrate working of
# Extract words starting with K in String List
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
x = []
for i in test_list:
x.extend(i.split())
for j in x:
if j.lower().find(K) == 0:
res.append(j)
# printing result
print("The filtered elements : " + str(res)) |
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G'] | Python - Extract words starting with K in String List
# Python3 code to demonstrate working of
# Extract words starting with K in String List
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
x = []
for i in test_list:
x.extend(i.split())
for j in x:
if j.lower().find(K) == 0:
res.append(j)
# printing result
print("The filtered elements : " + str(res))
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
[END] |
Python - Extract words starting with K in String List | https://www.geeksforgeeks.org/python-extract-words-starting-with-k-in-string-list/ | # Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using loop + split()
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
x = []
for i in test_list:
x.extend(i.split())
for i in x:
if i.startswith(K) or i.startswith(K.lower()) or i.startswith(K.upper()):
res.append(i)
# printing result
print("The filtered elements : " + str(res)) |
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G'] | Python - Extract words starting with K in String List
# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using loop + split()
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
x = []
for i in test_list:
x.extend(i.split())
for i in x:
if i.startswith(K) or i.startswith(K.lower()) or i.startswith(K.upper()):
res.append(i)
# printing result
print("The filtered elements : " + str(res))
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
[END] |
Python - Extract words starting with K in String List | https://www.geeksforgeeks.org/python-extract-words-starting-with-k-in-string-list/ | # Python3 code to demonstrate working of
# Extract words starting with K in String List
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
for i in test_list:
words = i.split()
startWords = list(filter(lambda x: x[0].lower() == K.lower(), words))
res.extend(startWords)
# printing result
print("The filtered elements : " + str(res)) |
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G'] | Python - Extract words starting with K in String List
# Python3 code to demonstrate working of
# Extract words starting with K in String List
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
for i in test_list:
words = i.split()
startWords = list(filter(lambda x: x[0].lower() == K.lower(), words))
res.extend(startWords)
# printing result
print("The filtered elements : " + str(res))
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
[END] |
Python - Extract words starting with K in String List | https://www.geeksforgeeks.org/python-extract-words-starting-with-k-in-string-list/ | # Python3 code to demonstrate working of
# Extract words starting with K in String List
import itertools
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
for i in test_list:
words = i.split()
startWords = list(itertools.filterfalse(lambda x: x[0].lower() != K.lower(), words))
res.extend(startWords)
# printing result
print("The filtered elements : " + str(res)) |
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G'] | Python - Extract words starting with K in String List
# Python3 code to demonstrate working of
# Extract words starting with K in String List
import itertools
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
for i in test_list:
words = i.split()
startWords = list(itertools.filterfalse(lambda x: x[0].lower() != K.lower(), words))
res.extend(startWords)
# printing result
print("The filtered elements : " + str(res))
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
[END] |
Python - Extract words starting with K in String List | https://www.geeksforgeeks.org/python-extract-words-starting-with-k-in-string-list/ | # importing reduce module
from functools import reduce
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
# Extract words starting with K in String List
# Using reduce() + split()
res = reduce(
lambda x, y: x + [ele for ele in y.split() if ele[0].lower() == K.lower()],
test_list,
[],
)
# printing result
print("The filtered elements : " + str(res))
# This code is contributed by Vinay Pinjala. |
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G'] | Python - Extract words starting with K in String List
# importing reduce module
from functools import reduce
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
# Extract words starting with K in String List
# Using reduce() + split()
res = reduce(
lambda x, y: x + [ele for ele in y.split() if ele[0].lower() == K.lower()],
test_list,
[],
)
# printing result
print("The filtered elements : " + str(res))
# This code is contributed by Vinay Pinjala.
#Output : The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
[END] |
Python - Prefix frequency in string list | https://www.geeksforgeeks.org/python-prefix-frequency-in-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Prefix frequency in List
# using loop + startswith()
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
test_sub = "gfg"
# Prefix frequency in List
# using loop + startswith()
res = 0
for ele in test_list:
if ele.startswith(test_sub):
res = res + 1
# printing result
print("Strings count with matching frequency : " + str(res)) |
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses'] | Python - Prefix frequency in string list
# Python3 code to demonstrate
# Prefix frequency in List
# using loop + startswith()
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
test_sub = "gfg"
# Prefix frequency in List
# using loop + startswith()
res = 0
for ele in test_list:
if ele.startswith(test_sub):
res = res + 1
# printing result
print("Strings count with matching frequency : " + str(res))
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
[END] |
Python - Prefix frequency in string list | https://www.geeksforgeeks.org/python-prefix-frequency-in-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Prefix frequency in List
# using sum() + startswith()
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
test_sub = "gfg"
# Prefix frequency in List
# using sum() + startswith()
res = sum(sub.startswith(test_sub) for sub in test_list)
# printing result
print("Strings count with matching frequency : " + str(res)) |
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses'] | Python - Prefix frequency in string list
# Python3 code to demonstrate
# Prefix frequency in List
# using sum() + startswith()
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
test_sub = "gfg"
# Prefix frequency in List
# using sum() + startswith()
res = sum(sub.startswith(test_sub) for sub in test_list)
# printing result
print("Strings count with matching frequency : " + str(res))
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
[END] |
Python - Prefix frequency in string list | https://www.geeksforgeeks.org/python-prefix-frequency-in-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Prefix frequency in List
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
test_sub = "gfg"
# Prefix frequency in List
# using loop + find()
res = 0
for ele in test_list:
if ele.find(test_sub) == 0:
res = res + 1
# printing result
print("Strings count with matching frequency : " + str(res)) |
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses'] | Python - Prefix frequency in string list
# Python3 code to demonstrate
# Prefix frequency in List
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
test_sub = "gfg"
# Prefix frequency in List
# using loop + find()
res = 0
for ele in test_list:
if ele.find(test_sub) == 0:
res = res + 1
# printing result
print("Strings count with matching frequency : " + str(res))
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
[END] |
Python - Prefix frequency in string list | https://www.geeksforgeeks.org/python-prefix-frequency-in-string-list/?ref=leftbar-rightbar | import re
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
test_sub = "gfg"
# Prefix frequency in List using re.match
res = 0
for ele in test_list:
if re.match(f"^{test_sub}", ele):
res += 1
# printing result
print("Strings count with matching frequency : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy |
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses'] | Python - Prefix frequency in string list
import re
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
test_sub = "gfg"
# Prefix frequency in List using re.match
res = 0
for ele in test_list:
if re.match(f"^{test_sub}", ele):
res += 1
# printing result
print("Strings count with matching frequency : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
[END] |