Open In App

Python List Comprehension and Slicing

Last Updated : 19 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. 

A list comprehension generally consists of these parts : 

  1. Output expression,
  2. Input sequence,
  3. A variable representing a member of the input sequence and
  4. An optional predicate part.
For example :

lst  =  [x ** 2  for x in range (1, 11)   if  x % 2 == 1] 

here, x ** 2 is output expression, 
      range (1, 11)  is input sequence, 
      x is variable and   
      if x % 2 == 1 is predicate part.
Another example :
lst=[x**2 if x%2==1 else x*2 for x in range(1,11)]

Example 1: 

Python3




# Python program to demonstrate list comprehension in Python 
   
# below list contains square of all odd numbers from 
# range 1 to 10 
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1
print (odd_square) 
   
# for understanding, above generation is same as, 
odd_square = [] 
for x in range(1, 11): 
    if x % 2 == 1
        odd_square.append(x**2
print (odd_square) 
   
# below list contains power of 2 from 1 to 8 
power_of_2 = [2 ** x for x in range(1, 9)] 
print (power_of_2)
#range 1 to 10
lst=[x**2 if x%2==1 else x*2 for x in range(1,11)]
print(lst)
 
#for understanding ,above "lst" is same as below "lst1"
lst1=[]
for x in range(1,11):
  if x%2==1:
      lst1.append(x**2)
  else:
    lst1.append(x*2)
print(lst1)
# below list contains prime and non-prime in range 1 to 50 
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] 
primes = [x for x in range(2, 50) if x not in noprimes] 
print (primes) 
   
# list for lowering the characters 
print ([x.lower() for x in ["A","B","C"]] )
   
# list which extracts number 
string = "my phone number is : 11122 !!"
   
print("\nExtracted digits"
numbers = [x for x in string if x.isdigit()] 
print (numbers) 
   
# A list of list for multiplication table 
a = 5
table = [[a, b, a * b] for b in range(1, 11)] 
   
print("\nMultiplication Table"
for i in table: 
    print (i)


Output: 

[1, 9, 25, 49, 81]
[1, 9, 25, 49, 81]
[2, 4, 8, 16, 32, 64, 128, 256]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
['a', 'b', 'c']

Extracted digits
['1', '1', '1', '2', '2']

Multiplication Table
[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
[5, 10, 50]

After getting the list, we can get a part of it using python’s slicing operator which has the following syntax: 

[start : stop : steps]  

which means that slicing will start from index start
 will go up to stop in step of steps. 
 Default value of start is 0, stop is last index of list
 and for step it is 1 

So [: stop] will slice list from starting till stop index and [start : ] will slice list from start index till end Negative value of steps shows right to left traversal instead of left to right traversal that is why [: : -1] prints list in reverse order.

Example 2: 

Python3




# Let us first create a list to demonstrate slicing
# lst contains all number from 1 to 10
lst =list(range(1, 11))
print (lst)
    
#  below list has numbers from 2 to 5
lst1_5 = lst[1 : 5]
print (lst1_5)
    
#  below list has numbers from 6 to 8
lst5_8 = lst[5 : 8]
print (lst5_8)
    
#  below list has numbers from 2 to 10
lst1_ = lst[1 : ]
print (lst1_)
    
#  below list has numbers from 1 to 5
lst_5 = lst[: 5]
print (lst_5)
    
#  below list has numbers from 2 to 8 in step 2
lst1_8_2 = lst[1 : 8 : 2]
print (lst1_8_2)
    
#  below list has numbers from 10 to 1
lst_rev = lst[ : : -1]
print (lst_rev)
    
#  below list has numbers from 10 to 6 in step 2
lst_rev_9_5_2 = lst[9 : 4 : -2]
print (lst_rev_9_5_2)


Output: 

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 3, 4, 5]
[6, 7, 8]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5]
[2, 4, 6, 8]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[10, 8, 6]

We can use the filter function to filter a list based on some condition provided as a lambda expression as the first argument and list as the second argument, an example of which is shown below :

Example 3:  

Python3




import functools
   
#  filtering odd numbers
lst = filter(lambda x : x % 2 == 1, range(1, 20))
print (list(lst))
    
#  filtering odd square which are divisible by 5
lst = filter(lambda x : x % 5 == 0
      [x ** 2 for x in range(1, 11) if x % 2 == 1])
print (list(lst))
    
#   filtering negative numbers
lst = filter((lambda x: x < 0), range(-5,5))
print (list(lst))
    
#  implementing max() function, using
print (functools.reduce(lambda a,b: a if (a > b) else b, [7, 12, 45, 100, 15]))


Output: 

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[25]
[-5, -4, -3, -2, -1]
100

 



Previous Article
Next Article

Similar Reads

Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Python | Slicing list from Kth element to last element
Python list slicing slices the list from start index till end - 1, specified as list elements. So its tricky when we require to also slice the last element of list. Trying to slice till list size + 1 gives an error. Let's discuss ways in which last element can be included during a list slice. Method #1 : Using None During list slicing, giving the d
6 min read
Python | Variable list slicing
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths according to the input given in other list. This problem has its potential application in web development. Let's discuss certain ways in which this can be done. Method #1 : Using itertools.islice() + list comprehension The list com
7 min read
Python | Alternate range slicing in list
List slicing is quite common utility in Python, one can easily slice certain elements from a list, but sometimes, we need to perform that task in non-contiguous manner and slice alternate ranges. Let's discuss how this particular problem can be solved. Method #1 : Using list comprehension List comprehension can be used to perform this particular ta
6 min read
Python | Get the substring from given string using list slicing
Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the index of a substring and more. Syntax of list slicin
4 min read
Python | Custom slicing in List
Sometimes, while working with Python, we can come to a problem in which we need to perform the list slicing. There can be many variants of list slicing. One can have custom slice interval and slicing elements. Let's discuss problem to such problem. Method : Using compress() + cycle() The combination of above functions can be used to perform this pa
2 min read
Python | Custom List slicing Sum
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths and its summation according to the input given in other list. This problem has its potential application in web development. Let’s discuss certain ways in which this can be done. Method #1 : Using itertools.islice() + sum() + list
7 min read
Python - Convert 2D list to 3D at K slicing
Sometimes, while working with Python lists, we can have a problem in which we need to convert a 2D list to 3D, at every Kth list. This type of problem is peculiar, but can have application in various data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]] , K
4 min read
Program to cyclically rotate an array by one in Python | List Slicing
Given an array, cyclically rotate the array clockwise by one. In this article, we will see how to cyclically rotate an array by one in Python. Example Input: arr = [1, 2, 3, 4, 5]Output: arr = [5, 1, 2, 3, 4]Reference: Program to cyclically rotate an array by one Python Program to Cyclically Rotate an Array by One in PythonBelow are the methods or
2 min read
Slicing List of Tuples in Python
Slicing, a powerful feature in Python, allows us to extract specific portions of data from sequences like lists. When it comes to lists of tuples, slicing becomes a handy tool for extracting and manipulating data. In this article, we'll explore five simple and versatile methods to slice lists of tuples in Python, accompanied by code examples. Slici
2 min read
three90RightbarBannerImg