- It is very easy and compact way of creating list objects from any iterable objects (like list, tuple, dictionary, range etc.) based on some condition.
Syntax
Python
my_list=[expression for item in list if condition]
Example
Python
s=[ x*x for x in range(1,11)]
print(s)
v=[2**x for x in range(1,6)]
print(v)
m=[x for x in s if x%2==0]
print(m)
Output
PowerShell
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[2, 4, 8, 16, 32]
[4, 16, 36, 64, 100]
Example
Python
words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
l=[w[0] for w in words]
print(l
Output
PowerShell
['B', 'N', 'V', 'C']
Example
Python
num1=[10,20,30,40]
num2=[30,40,50,60]
num3=[ i for i in num1 if i not in num2]
print(num3)
num4=[i for i in num1 if i in num2]
print(num4)
Output
PowerShell
[10, 20]
[30, 40]
Example
Python
words="the quick brown fox jumps over the lazy dog".split()
print(words)
l=[[w.upper(),len(w)] for w in words]
print(l)
Output
PowerShell
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]
Question
Write a program to display unique vowels present in the given word?
Python
vowels=['a','e','i','o','u']
word=input("Enter the word to search for vowels: ")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)
print("The number of different vowels present in",word,"is",len(found))
Output
PowerShell
Enter the word to search for vowels: internetknowledgehub
['i', 'e', 'o', 'u']
The number of different vowels present in internetknowledgehub is 4
Nested Lists
- Sometimes we can take one list inside another list. Such type of lists are called nested lists.
Example
Python
n=[10,20,[30,40]]
print(n)
print(n[0])
print(n[2])
print(n[2][0])
print(n[2][1])
Output
PowerShell
[10, 20, [30, 40]]
10
[30, 40]
30
40
Note
- We can access nested list elements by using index just like accessing multi dimensional array elements.
Nested List as Matrix
- In Python we can represent matrix by using nested lists.
Example
Python
n=[[10,20,30],[40,50,60],[70,80,90]]
print(n)
print("Elements by Row wise:")
for r in n:
print(r)
print("Elements by Matrix style:")
for i in range(len(n)):
for j in range(len(n[i])):
print(n[i][j],end=' ')
print()
Output
PowerShell
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
Elements by Row wise:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
Elements by Matrix style:
10 20 30
40 50 60
70 80 90
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!