Related Articles

Related Articles

Python | Truncate a list
  • Last Updated : 04 Jan, 2019

Sometimes there is a requirement to restrict the list size to a particular number and remove all the elements from list which occur after a certain number as decided as list size. This is a useful utility for web development using Python. Let’s discuss certain ways in which this can be performed.

Method #1 : Using pop()
pop function can be repeated a number of times till size of the list reaches the threshold required as the size of the list. This uses a whole loop and hence is comparatively tedious.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# to truncate list using pop()
  
# initializing list  
test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# size desired
k = 5
  
# using pop()
# to truncate list 
n = len(test_list)
for i in range(0, n - k ):
    test_list.pop()
  
# printing result
print ("The truncated list is : " +  str(test_list))

chevron_right


Output:

The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10]
The truncated list is : [1, 4, 5, 6, 7]

 
Method #2 : Using del + list slice
del operator can be used to delete all the elements that appear after the specific index, which is handled by the list slicing technique.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# to truncate list 
# using del + list slicing
  
# initializing list  
test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# size desired
k = 5
  
# using del + list slicing
# to truncate list 
del test_list[5:]
  
# printing result
print ("The truncated list is : " +  str(test_list))

chevron_right


Output:



The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10]
The truncated list is : [1, 4, 5, 6, 7]

 
Method #3 : Using list slicing
In this method, we just slice the first K elements and ignore all the elements that occur after K elements. This is most pythonic and recommended method to perform this task.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# to truncate list 
# using list slicing
  
# initializing list  
test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# size desired
k = 5
  
# using list slicing
# to truncate list 
res = test_list[0 : 5]
  
# printing result
print ("The truncated list is : " +  str(res))

chevron_right


Output:

The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10]
The truncated list is : [1, 4, 5, 6, 7]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :