Iterations

Consider you have a given list of positive and negative numbers, put all the positive numbers in one list and negative numbers in the other list.

Solution: Create two lists, X and Y. Initialize both of them to [].
Now check each number in the list.If the number is positive put it in X and if the number is negative put it in Y.

Program



L= [1, 2, 5, 7, -1, -2, -3, -4]
P=[]
N=[]
for num in L:
 if(num >0):
   P.append(num)
 elif (num<0):
   N.append(num)
print('positive numbers \t:',P)
print('negative numbers \t:',N)
>>>
Output

The list of positive numbers : [1, 2, 5, 7]
The list of negative numbers : [-1, -2, -3, -4]

You have a list of characters. Suppose you have to separate out into 2 lists. One list should be having only vowel and other list should have only constants character.
Create two strings: str1 and str2. 
check each character in the given string. 
If it is a vowel, concatenate it with str1 otherwise concatenate it with str2.

Program

string =input('Enter a string\t:')
str1=""
str2=""
for i in string:
   if((i =='a')|(i=='e')|(i=='i')|(i=='o')|(i=='u')):
      str1=str1+str(i)
   else :
      str2=str2+str(i)
print('The string containing the vowels is '+str1)
print('The string containing consonants '+str2)
Through Iterator:
s = 'college'
t = iter(s)
vow = ''
cons = ''
try:
   while True:
           x = t._next_()
           if x in ['a','e','i','o','u']:
                            vow += x
           else:
                            cons += x
except StopIteration:
   print( 'String - ' + s + '\nVowels - ' + vow + '\
                                 nConsonents - ' + cons )
raise StopIteration
How will you iterate Tuple?
T=(1, 2, 3,4)
for i in T:
  print(i)
print(T)
>>>
Output

1
2
3
4
How will you iterate dictionary?
Dictionary={'this is book':1234, 'this is novel':599}
print(Dictionary)
for i in Dictionary:
   print(i)
>>>
Output

========== RUN C:/Python/Iterations/for dic.py ==========
{'this is book':1234, 'this is novel': 599}
this is book
this is novel
>>>
What is Iterator in Python?

Iterator takes an iterable object and helps to traverse the object.An iterator can be set on a list using the following:

= iter(
The iterator can move to the next element, using the next() method.
An iterator can iterate through any iterable object including lists, tuples, strings or a directory.
When there are no more elements then a StopIteration exception is raised.

Through Iterator:
L = [ 1,2,3,-4,-5,-6]
P = []
N = []
t = iter(L)
try:
while True:
        x = t. next ()
        if x >= 0:
                    P.append(x)
        else:
                    N.append(x)
except StopIteration:
   print( 'original List- ' , L , '\nList containing the
             positive numbers- ', P , '\nList containing the
                                    negative numbers- ', N )
raise StopIteration
  • _next_(): The next function helps in iterating over the value of the iterable object.
  • _iter_(): It helps in creating a user defined iterable object.
  • yield(): It does not return anything.
You have 2 lists and have to combine both lists.Write a program to sort the final list.
l1 = [ 1, 6, 2, 4, 5]
l2 = [ 7, 4, 3, 2, 4]
i1 = iter(l1)
i2 = iter(l2)
l3 = sorted( list(i1) + list(i2) )
Write a generator to produce a Fibonacci series.

Solution:

def fib(n):
  a=[]
  if n==1:
   a[0]=1
   yield 1
  elif n==2:
   a[1]=1
   yield 1
  else:
   a[0]=1
   a[1]=1
   i=2
   while i<=n:
     a[i]=a[i-1]+a[i-2]
    yield (a[i])

n=int(input('Enter the number \t:'))
fibList=fib(n)
for i in fibList:
print(i)
>>>

Comprehensions can be used for lists, dictionary and set comprehension.The following illustration explains the use of comprehensions to generate lists in various cases:

The range (n) function generates numbers up to n.
The first comprehension generates the list of numbers which are cubes of all the numbers generated by the range function.

The second comprehension works in the same way but generates 3 to the power of x.

The third comprehension generates a list having numbers generated by the range (n) function, which are multiples of 5.

What is the difference between yield and return in python?

Yield is used to convert a regular Python function into a generator. Return is generally used for the end of the execution and “returns” the result to the caller statement. It replace the return of a function to suspend its execution without destroying local variables.