Python | Move given element to List Start
Last Updated :
15 Apr, 2023
The conventional problem involving the element shifts has been discussed many times earlier, but sometimes we have strict constraints performing them, and knowledge of any possible variation helps. This article talks about one such problem of shifting K’s at the start of the list, catch here is it checks for just K’s excluding the conventional ‘None’ (False) values. Let’s discuss certain ways in which this can be performed.
Method #1: Using list comprehension + isinstance() In this method, we perform the operation of shifting in 2 steps. In 1st step, we get all the values that we need to get at the front and at the end we just push the K’s to the front. The instance method is used to filter out the Boolean False entity.
Python3
test_list = [ 1 , 4 , None , "Manjeet " , False , 4 , False , 4 , "Nikhil" ]
print ( "The original list : " + str (test_list))
K = 4
temp = [ele for ele in test_list if ele ! =
K and ele or ele is None or isinstance (ele, bool )]
res = [K] * ( len (test_list) - len (temp)) + temp
print ( "The list after shifting K's to start : " + str (res))
|
Output
The original list : [1, 4, None, 'Manjeet ', False, 4, False, 4, 'Nikhil']
The list after shifting K's to start : [4, 4, 4, 1, None, 'Manjeet ', False, False, 'Nikhil']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using list comprehension + isinstance() + list slicing This method is similar to the above method, the only modification is that to reduce number of steps, list slicing is used to attach the K’s to perform whole task in just 1 step.
step-by-step approach
- Initialize the input list test_list as given in the problem statement.
- Print the original list for verification.
- Initialize the value of K to be moved to the start of the list.
- Create a list comprehension that does the following:
- Generate a list of K values with the same length as test_list.
- Append the remaining values of the list that are not equal to K and satisfy one of the following conditions:
- Not an integer or boolean value.
- A boolean value that is False.
- Use list slicing to remove the K values that were added in step 1.
- Assign the resulting list to the variable res.
- Print the resulting list for verification.
Python3
test_list = [ 1 , 4 , None , "Manjeet" , False , 4 , False , 4 , "Nikhil" ]
print ( "The original list : " + str (test_list))
K = 4
res = ([K] * len (test_list) + [ele for ele in test_list if ele ! = K and ele or not isinstance (ele, int )
or isinstance (ele, bool )])[ len ([ele for ele in test_list if ele ! = K and ele or not isinstance (ele, int )
or isinstance (ele, bool )]):]
print ( "The list after shifting K's to end : " + str (res))
|
Output
The original list : [1, 4, None, 'Manjeet', False, 4, False, 4, 'Nikhil']
The list after shifting K's to end : [4, 4, 4, 1, None, 'Manjeet', False, False, 'Nikhil']
Time complexity: O(n)
Auxiliary space: O(n)
Method #3 : Using count() , remove(), extend() methods
Python3
test_list = [ 1 , 4 , None , "Manjeet" , False , 4 , False , 4 , "Nikhil" ]
print ( "The original list : " + str (test_list))
K = 4
x = test_list.count(K)
while K in test_list:
test_list.remove(K)
res = [K] * x
res.extend(test_list)
print ( "The list after shifting K's to start : " + str (res))
|
Output
The original list : [1, 4, None, 'Manjeet', False, 4, False, 4, 'Nikhil']
The list after shifting K's to start : [4, 4, 4, 1, None, 'Manjeet', False, False, 'Nikhil']
Time complexity: O(n), where n is the number of elements in the list.
Auxiliary space: O(x), where x is the number of occurrences of K in the list.
Method #4 : Using append() and extend() methods
Python3
test_list = [ 1 , 4 , None , "Manjeet" , False , 4 , False , 4 , "Nikhil" ]
print ( "The original list : " + str (test_list))
K = 4
a = []
b = []
for i in test_list:
if (i = = K):
a.append(i)
else :
b.append(i)
a.extend(b)
print ( "The list after shifting K's to start : " + str (a))
|
Output
The original list : [1, 4, None, 'Manjeet', False, 4, False, 4, 'Nikhil']
The list after shifting K's to start : [4, 4, 4, 1, None, 'Manjeet', False, False, 'Nikhil']
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), because it creates two additional lists, a and b, which together can hold all the elements of the input list.
Method 5: Using filter() and lambda function
Take a list of mixed data types and moves all occurrences of a given element (K) to the beginning of the list, while preserving the order of the other elements. It does this using the filter() and lambda functions to separate the K elements from the non-K elements, and then concatenating the two lists.
Python3
test_list = [ 1 , 4 , None , "Manjeet " , False , 4 , False , 4 , "Nikhil" ]
print ( "The original list : " + str (test_list))
K = 4
K_list = list ( filter ( lambda x: x = = K, test_list))
non_K_list = list ( filter ( lambda x: x ! = K, test_list))
res = K_list + non_K_list
print ( "The list after shifting K's to start : " + str (res))
|
Output
The original list : [1, 4, None, 'Manjeet ', False, 4, False, 4, 'Nikhil']
The list after shifting K's to start : [4, 4, 4, 1, None, 'Manjeet ', False, False, 'Nikhil']
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as we are creating two new lists.
Similar Reads
Python - Move Element to End of the List
We are given a list we need to move particular element to end to the list. For example, we are given a list a=[1,2,3,4,5] we need to move element 3 at the end of the list so that output list becomes [1, 2, 4, 5, 3]. Using remove() and append()We can remove the element from its current position and t
3 min read
Python Program to Swap Two Elements in a List
In this article, we will explore various methods to swap two elements in a list in Python. The simplest way to do is by using multiple assignment. Example: [GFGTABS] Python a = [10, 20, 30, 40, 50] # Swapping elements at index 0 and 4 # using multiple assignment a[0], a[4] = a[4], a[0] print(a) [/GF
2 min read
Split Elements of a List in Python
Splitting elements of a list in Python means dividing strings inside each list item based on a delimiter. split() Method is the easy and most straightforward method to split each element is by using the split() method. This method divides a string into a list based on a delimiter. Here's how we can
2 min read
Swap elements in String list - Python
Swapping elements in a string list means we need to exchange one element with another throughout the entire string list in Python. This can be done using various methods, such as using replace(), string functions, regular expressions (Regex), etc. For example, consider the original list: ['Gfg', 'is
3 min read
Swap tuple elements in list of tuples - Python
The task of swapping tuple elements in a list of tuples in Python involves exchanging the positions of elements within each tuple while maintaining the list structure. Given a list of tuples, the goal is to swap the first and second elements in every tuple. For example, with a = [(3, 4), (6, 5), (7,
3 min read
Remove Negative Elements in List-Python
The task of removing negative elements from a list in Python involves filtering out all values that are less than zero, leaving only non-negative numbers. Given a list of integers, the goal is to iterate through the elements, check for positivity and construct a new list containing only positive num
3 min read
Python | Remove given element from the list
Given a list, write a Python program to remove the given element (list may have duplicates) from the given list. There are multiple ways we can do this task in Python. Let's see some of the Pythonic ways to do this task. Example: Input: [1, 8, 4, 9, 2] Output: [1, 8, 4, 2] Explanation: The Element 9
7 min read
Python | Operation to each element in list
Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
3 min read
Python | Remove given element from list of lists
The deletion of elementary elements from list has been dealt with many times, but sometimes rather than having just a one list, we have list of list where we need to perform this particular task. Having shorthands to perform this particular task can help. Let's discuss certain ways to perform this p
6 min read
Move One List Element to Another List - Python
The task of moving one list element to another in Python involves locating a specific element in the source list, removing it, and inserting it into the target list at a desired position. For example, if a = [4, 5, 6, 7, 3, 8] and b = [7, 6, 3, 8, 10, 12], moving 10 from b to index 4 in a results in
3 min read