UNIT 2 List
UNIT 2 List
LIST
List items are ordered, changeable, and allow
duplicate values.
List items are indexed, the first item has
index [0], the second item has index [1] etc.
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
O/P: ['apple', 'banana', 'mango']
With list comprehension you
can do all that with only one
line of code:
Example:
fruits = ["apple", "banana", "cherry", "kiwi",
"mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
O/P:
['apple', 'banana', 'mango']
The Syntax of List
Comprehension
newlist = [expression for item in iterable if
condition == True]
The return value is a new list, leaving the old
list unchanged.
List Built-in Methods
Dictionary
Dictionaries are used to store data values in
key:value pairs.
A dictionary is a collection which is ordered*,
changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have
keys and values:
# Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
O/P: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Methods
Use of while loops in python
The Python while loop iteration of a code
block is executed as long as the given
Condition, i.e., conditional_expression, is
true.
Syntax of the Python while loop
Statement
while Condition:
Statement
i=1
while i<=10:
print(i, end=' ')
i+=1
O/P: 1 2 3 4 5 6 7 8 9 10
--------
i=0
while i< 3:
print(i)
i += 1
else:
print(0)
O/P:
0
1
2
0
----------------
i=1
while i<51:
if i%5 == 0 or i%7==0 :
print(i, end=' ')
i+=1
O/P: 5 7 10 14 15 20 21 25 28 30 35 40 42 45
49 50
Write a program to check an input
number is prime or not.
n= int(input("Enter Number:"))
count=0
i=1
while(i<=n):
if(n%i==0):
count=count+1
i=i+1
if(count==2):
print("prime number")
else:
print("not prime number")