Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. List, Tuples and Dictiona...
  5. Advanced List Processing

Advanced List Processing

List Comprehension

Python supports computed lists called list comprehensions.

Syntax:

list = [expression for variable in sequence]
list = [expression for item in iterable if condition == True
  • Where the expression is evaluated once, for every item in sequence.
  • Expression is the current item in the iteration. It is also the outcome which you can manipulate before it ends ups like a list item in the new list
  • The expression can also contain conditions to manipulate the outcome
  • Expression can also be a constant

List comprehensions help programmers to create lists in a concise way. This is beneficial to make new lists where each element is the obtained by applying some operations to each member of another sequence or iterable. An iterable is an object that can be used repeatedly in subsequent loop statements.

List comprehension is used to create a subsequence of those elements that satisfy a certain condition

Example

To create a list with square of numbers

n=int(input("Enter a number:"))
x = [i * i for i in range(1,n)]
print("New List:",x)

Output

Enter a number: 10
New List: [1, 4, 9, 16, 25, 36, 49, 64, 81]

Use of if condition for list comprehension

subjects=["python","maths", "chemistry"]
x = [i for i in subjects if 'a' not in i]
print("New list x:",x)

Output

New list x: ['python', 'chemistry']

Use of condition for list comprehension

subjects=["python","maths", "chemistry"]
x = [i for i in subjects if i != 'maths']
print("New list x:",x)

Output

New list x: ['python', 'chemistry']

Accept numbers only less than 5

newlist = [x for x in range(20) if x % 5 == 0]
print("Newlist: ",newlist)

Output

Newlist:  [0, 5, 10, 15]

Manipulation of expression

subjects=["python","maths", "chemistry"]
snew = [x.upper() for x in subjects]
print("New list:",snew)

Output

New list: ['PYTHON', 'MATHS', 'CHEMISTRY']

Manipulating expression with condition

list1 = [10,20,21,23,24,25,26]
newlist1 = [0 if (x % 2 == 0) else 1 for x in list1]
print("New List:", newlist1)

Output

New List: [0, 0, 1, 1, 0, 1, 0]

Expression as a constant value

list1 = ["python", "chemistry"]
newlist1 = [1 for x in list1]
print("New list:", newlist1)

Output

New list: [1, 1]

Advantages of list comprehension

  • List comprehensions are concise and easy to read, at least for simple expressions
  • They are usually faster than equivalent for loops, sometimes much better
  • They can also be used for filtering

Disadvantages

They are harder to debug because you can’t put a print statement inside the loop

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments