1️⃣ List Comprehension

  • List comprehension shortens the code and provides the respective output in list.

    Scenario 1: We have list of numbers in ‘nums’ list and we want only even numbers in another ‘evens’ list. So lets try it using normal for loop approach.

💻 Example 1:

1
2
3
4
5
6
7
# get even number list from nums using for loop
nums = [1,2,3,4,5,6]
evens = []
for n in nums:
    if n%2==0:
        evens.append(n)
print(evens)

✅ Output:

[2,4,6]

Similarly we can achieve above output using list comprehension approach:

💻 Example 2:

1
2
3
4
# implementation using list comprehension
nums = [1,2,3,4,5,6]
evens = [n for n in nums if n%2==0]
print(evens)

✅ Output:

[2,4,6]

Scenario 2: We have string ‘mystr’ containing characters we want a new list which contains the characters presents at only even positions.

💻 Example 1:

1
2
3
4
5
6
7
8
9
# implementation using for loop
mystr = 'abcdefghijk'

mylist = []
for i in range(len(mystr)):
    if i%2==0:
        mylist.append(mystr[i])

print(mylist)

✅ Output:

['a','c','e','g','i','k']

Similarly we can achieve above output using list comprehension approach:

💻 Example 2:

1
2
3
4
# implementation using list comprehension
mystr = 'abcdefghijk'
mylist = [mystr[i] for i in range(len(mystr)) if i%2==0]
print(mylist)

✅ Output:

['a','c','e','g','i','k']