In this section, we are going to understand python list slicing and list comprehension.
What is list slicing?
As the name suggest, slice means – to cut something into smaller pieces(slices). List slicing is the process of extracting a portion of list from an original list. In list slicing we’re going to cut a list based on what we want (such as where to start, stop and what increment to slice by).
What is List comprehension?
List comprehension is generating a list based on an existing list. It provides an elegant way to define and create a new lists based on existing lists.
List Slicing
As we are going to slice a list, so let’s first create a list−
>>> mylist = ["Which ", "Language ", "To ", "Choose ", "Difficult, ", "Python ", "Java ", "Kotlin ", "Many more"]
List can be indexed backwards, starting at -1 (last element) and increasing by -1. So -1 would be the last elment, -2 would be the second last.
>>> mylist_slice1 = mylist[0: -1:2] >>> mylist_slice1 ['Which ', 'To ', 'Difficult, ', 'Java ']
When slicing a list, we must call our list first (mylist in our case) followed by our requirements for slicing. These must be enclosed in brackets []. The argument we may need to pass inside the [] are −
- First argument, index to start slicing.
- Second argument, index to stop slicing.
- Third argument, step/increment to slice by(optional).
So in the end, this will look something like −
mylist[START: STOP:STEP] >>> mylist_slice2 = mylist[1:-1:2] >>> mylist_slice2 ['Language ', 'Choose ', 'Python ', 'Kotlin ']
List Comprehension
As you know my now (from above), list comprehension is generating a new list from the existing one. So let’s first create a list(original list), i’m using the range() function to generate temporary list of numbers for our list comprehension.
>>> mylist1 = [x for x in range(0, 40)] >>> mylist1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39] >>> >>> mylist2 = [x for x in range(0,41) if x%2 == 0] >>> mylist2 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40]
Let’s understand what’s going on above, we first create a temporary variable name “x” followed by a for loop that iterates through a range from 0 to 40 inside the brackets and when we execute it, it generates a list of numbers from 0 to 39. Then we create another list and we added condition to it, condition was “if x%2 == 0”. It means we are looking for even numbers only.
Let’s create another list using strings for list comprehension.
>>> strlist = ["This", "Is", "A" , "List" , "Of", "Strings", "For", "List", "Comprehension"] >>> print([x.lower() for x in strlist]) ['this', 'is', 'a', 'list', 'of', 'strings', 'for', 'list', 'comprehension']
Above we have a string list, and we have lower-cased the list items using list comprehension.