-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path41)List_Comprehension_Program.py
More file actions
54 lines (28 loc) · 1.39 KB
/
41)List_Comprehension_Program.py
File metadata and controls
54 lines (28 loc) · 1.39 KB
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
40
41
42
43
44
45
46
47
48
49
50
#List comprehension offers a shorter syntax when you want to create a new list based on the values
# of an existing list.
#Example:
#Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
#Without list comprehension you will have to write a for statement with a conditional test inside:
fruits = ["apple","banana","cherry","custurdapple","mango"]
newlist = []
for x in fruits:
if 'a' in x :
newlist.append(x)
print(newlist)
############################################################################################################
#With list comprehension you can do all that with only one line of code:
#Example
fruits = ["apple","banana","grapes","watermelon","cherry","mango","kiwi","custardapple"]
newlist = [x for x in fruits if 'a']
print(newlist)
#############################################################################################################
#The Syntax
#newlist = [expression for item in iterable if condition == True]
#The return value is a new list, leaving the old list unchanged.
##############################################################################################################
# Condition
# The condition is like a filter that only accepts the items that evaluate to True.
#Example
#Only accept items that are not "apple":
newlist = [x for x in fruits if x != "apple"]
print(newlist)