View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
The manipulation of lists is quite common in day-day programming. One can come across various issues where one wishes to perform using just one-liners. One such problem can be of moving a list element to the rear [ end of list ]. Let’s discuss certain ways in which this can be done.
Method #1 : Using append[] + pop[] + index[]
This particular functionality can be performed in one line by combining these functions. The append function adds the element removed by pop function using the index provided by index function.
test_list
=
[
'3'
,
'5'
,
'7'
,
'9'
,
'11'
]
print
[
"The original list is : "
+
str
[test_list]]
test_list.append[test_list.pop[test_list.index[
5
]]]
print
[
"The modified element moved list is : "
+
str
[test_list]]
Output :
The original list is : ['3', '5', '7', '9', '11'] The modified element moved list is : ['3', '7', '9', '11', '5']
Method #2 : Using sort[] + key = [__eq__]
The sort method can also be used to achieve this particular task in which we provide the key as equal to
the string we wish to shift so that it is moved to the end.
test_list
=
[
'3'
,
'5'
,
'7'
,
'9'
,
'11'
]
print
[
"The original list is : "
+
str
[test_list]]
test_list.sort[key
=
'5'
.__eq__]
print
[
"The modified element moved list is : "
+
str
[test_list]]
Output :
The original list is : ['3', '5', '7', '9', '11'] The modified element moved list is : ['3', '7', '9', '11', '5']
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
The cyclic rotations have been discussed in the earlier articles. But sometimes, we just require a specific task, a part of rotation i.e shift last element to first element in list. This has the application in day-day programming in certain utilities. Let’s discuss certain ways in which this can be achieved.
Method #1 : Using list slicing and “+
” operator
The combination of these functions can be used to perform the task of a single shift in list. The last element is added to the rest of the list to achieve this task using slicing.
test_list
=
[
1
,
4
,
5
,
6
,
7
,
8
,
9
,
12
]
print
[
"The original list is : "
+
str
[test_list]]
test_list
=
test_list[
-
1
:]
+
test_list[:
-
1
]
print
[
"The list after shift is : "
+
str
[test_list]]
Output:
The original list is : [1, 4, 5, 6, 7, 8, 9, 12] The list after shift is : [12, 1, 4, 5, 6, 7, 8, 9]
Method #2 : Using insert[] + pop[]
This functionality can also
be achieved using the inbuilt functions of python viz. insert[] and pop[]
. The pop function returns the last element and that is inserted at front using the insert function.
test_list
=
[
1
,
4
,
5
,
6
,
7
,
8
,
9
,
12
]
print
[
"The original list is : "
+
str
[test_list]]
test_list.insert[
0
, test_list.pop[]]
print
[
"The list after shift is : "
+
str
[test_list]]
Output:
The original list is : [1, 4, 5, 6, 7, 8, 9, 12] The list after shift is : [12, 1, 4, 5, 6, 7, 8, 9]