Python

Python: Remove Elements from List by Value

Lists are ordered sequences that can contain a wide range of object types. Members on lists can also be duplicated. Lists in Python are equivalent to arrays in other programming languages. There is, however, one significant difference. Arrays can only have elements of the same data type, whereas Python lists can have items of different data types.

Python Lists have several methods for removing elements from the list.

Examples:

Input:

givenlist=["hello", "this", "is", "Btech", "Geeks" ,"is" ] , value=is

Output:

["hello", "this", "Btech", "Geeks"]

Remove Elements from the List by Values

There are several ways to remove elements from the list by values some of them are:

Method #1:Using remove() function

The remove method removes a list element based on its value rather than its index. When more than one element matches the provided value, the first matching element (the one with the lowest index) is removed. This is useful when you know which element needs to be removed ahead of time and don’t want to waste time looking for its index before removing it.

Let us now use the remove() function to remove the first instance of an element ‘is’.

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, value):
    # removing the value using remove()
    givenlist.remove(value)
    # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value which is to be removed
value = 'is'
# passing list and value to removeValue function to remove the element
print(removeValue(givenlist, value))

Output:

['hello', 'this', 'Btech', 'Geeks', 'is']

If we use the remove() function to remove an element from a list that does not exist, what happens? In that case, Value Error will be returned.

Method #2: Removing given value using remove() if exist

To avoid the ValueError, we check to see if the value is already in the list and then remove it.

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, value):
  # checking if value is present in givenlist
    if value in givenlist:
     # removing the value using remove()
        givenlist.remove(value)
    # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value which is to be removed
value = 'is'
# passing list and value to removeValue function to remove the element
print(removeValue(givenlist, value))

Output:

['hello', 'this', 'Btech', 'Geeks', 'is']

Method #3:Removing all occurrences of  given value

As we saw in the previous examples, the remove() function always deletes the first occurrence of the given element from the list. To delete all occurrences of an element, we must use the remove() function in a loop until all occurrences are gone.

So we use while loop to achieve that.

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, value):
    # using while loop to remove all occurrences of given value
    while(value in givenlist):
        # removing the value using remove()
        givenlist.remove(value)
       # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value which is to be removed
value = 'is'
# passing list and value to removeValue function to remove the element
print(removeValue(givenlist, value))

Output:

['hello', 'this', 'Btech', 'Geeks']

Method #4: Using values, remove all occurrences of multiple elements from a list.

Assume we have a list of numbers and another list of values that we want to remove from the first list. We want to remove all of the elements from list2 from list1.

We’ve created a separate function for this, which takes two different lists as arguments.

  • The first is the givenlist.
  • The elements we want to remove are listed in the second list(valuelist)

It deletes all occurrences from the original list for each element in the second list.

Approach:

  • Traverse the value list
  • Using while loop remove all occurrences of the value from given list.
  • Return given list

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, valuelist):
    # Traverse the value list
    for value in valuelist:
       # using while loop to remove all occurrences of given value
        while(value in givenlist):
            # removing the value using remove()
            givenlist.remove(value)
           # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value list which is to be removed
valuelist = ['is', 'hello', 'this']
# passing list and valuelist to removeValue function to remove the element
print(removeValue(givenlist, valuelist))

Output:

['Btech', 'Geeks']

Related Programs:

Python: Remove Elements from List by Value Read More »

Python Programming – Compound statement Built-in functions

In this Page, We are Providing Python Programming – Compound statement Built-in functions. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Compound statement Built-in functions

Built-in functions

Till now, the discussed functions need to be defined before using it in a program; such functions are called user-defined functions. Python has a number of functions that are always available. These are called built-in functions. They are listed here in alphabetical order.

                   abs ( )                                  all ( )                                          any ( )
                   basestring ( )                       bin ( )                                        bool ( )
                   bytearray ( )                        callable ( )                                 chr ( )
                   classmethod ( )                   cmp ( )                                       compile ( )
                   complex ( )                          delattr ( )                                    diet ( )
                   dir ( )                                   divmod ( )                                  enumerate ( )
                  eval ( )                                  execfile ( )                                   file ( )
                  filter ( )                                float ( )                                      format ( )
                  frozenset ( )                        getattr ( )                                   globals ( )
                  hasattr ( )                            hash ( )                                         help ( )
                  hex ( )                                 id ( )                                            input ( )
                  int ( )                                  isinstance ( )                             issubclass ( )
                  iter ( )                                  len ( )                                         list ( )
                  locals ( )                             long ( )                                         map ( )
                  max ( )                               memoryview ( )                            min ( )
                  next ( )                              object ( )                                        oct ( )
                 open ( )                              ord ( )                                           pow ( )
                 print ( )                            property ( )                                      range ( )
                raw_input ( )                      reduce ( )                                     reload ( )
                repr ( )                              reversed ( )                                   round ( )
                set ( )                                setattr ( )                                        slice ( )
               sorted ( )                           staticmethod ( )                              str ( )
               sum ( )                               super ( )                                         tuple ( )
               type ( )                               unichr ( )                                       Unicode ( )
               vars ( )                              xrange ( )                                        zip ( )
             import ( )                           apply ( )                                         buffer ( )
              coerce ( )                          intern ( )

Some of the above built-in functions are discussed below:

abs ( x )
Return the absolute value of a number. The argument may be a plain or long integer or a floating-point number. If the argument is a complex number, its magnitude is returned.

>>> abs ( - 34 )
34 
>>> abs ( 34 . 5 )
34 . 5
>>> abs ( -3 -4 j )
5 . 0

all ( iterable )
Return True, if all elements of the iterable are true (or if the iterable is empty).

>>> all ( [ True , 10 ] )
True
>>> all ( [ True , 10 , 0 ] )
False
>>> all ( ( ) )
True

any ( iterable )
Return True, if any element of the iterable is true. If the iterable is empty, return False.

>>> any ( [ 0 , 5 , -3 ] )
True
>>> any (  [0 , False  , -3 ] )
True
>>> any ( ( ) )
False

bin ( x )
Convert an integer number to a binary string.

>>> bin ( 8 )
' 0b1000 '
>>> bin ( 27 )
' 0b11011 '
>>> (27) . hit_length ( )
5
>>> bin ( -1327 )
' -0b100101111 '
>>> ( -1327 ) . bit_length ( )
11

bool ( [ x ] )
Convert a value to a boolean. If x is false or omitted, this returns False; otherwise, it returns True. If no argument is given, this function returns False.

>>> bool ( 5 )
True 
>>> bool ( -5 )
True
>>> bool ( 0 )
False 
>>> bool ( ' hi ' )
True
>>> bool ( )
False 
>>> bool ( '' )
False 
>>> bool ( None )
False
>>> bool ( ' \ n ' ) 
True
>>> bool ( [ 0 ] )
True
>>> bool ( ( None , ) ) 
True

chr ( i )
Return a string of one character whose ASCII-8 code is the integer i. This is the inverse of ord ( ). The argument must be in the range [0,255]; ValueError will be raised if i is outside that range.

>>> for i in range ( 33 , 95 ) : print i , ' =  ' , chr ( i )
. . . 
33 = !
34 = "
35 = #
36 = $
3 7 = %
38 = &
39 = '
40 = (
41 = )
42 = *
43 = +
44 = ,
45 = -
46 = .
47 = /
48 = 0 
49 = 1
50 = 2
51 = 3
52 = 4
53 = 5 
55 = 7
56 = 8
57 = 9
58 = :
59 = ;
60 = < 
61 = = 
62 = >
63 = ?
64 = 0
65 = A
66 = B
67 = C
68 = D
69 = E
70 = F
71 = G
72 = H
73 = I
74 = J
75 = K
76 = L
77 = M
78 = N
79 = O
80 = P
81 = Q
82 = R
83 = S
84 = T
85 = U
86 = V
87 = W
88 = X
89 = Y
90 = Z
91 = [
92 = \
93 = ]
94 = A

cmp ( x , y )
Compare the two objects x and y, and return an integer according to the outcome. The returned value is negative, if xc’y, zero, if x==y, and strictly positive, if x>y.

>>> cmp ( 2 . 5 , 5 . 2 )
-1 
>>> cmp ( 5 . 2 , 5 . 2 )
0 
>>> cmp ( 5 . 2 , 2 . 5 ) 
1
>>> cmp ( ' hi ' , ' hello ’ )
1
>>> cmp ( 'hello ' , ' hi ' )
-1

complex ( [ real [ , imag ] ] )
Create a complex number with the value real+imag* j, or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex).

If imag is omitted, it defaults to zero. If both arguments are omitted, the function returns 0 j. When converting from a string, the string must not contain whitespace around the central + or – operator. For example, complex ( ‘ 1 + 2 j ‘ ) is fine, but complex (‘1 + 2 j ‘ ) raises ValueError.

>>> complex ( )
Oj
>>> complex ( 2 . 51 )
( 2 . 51+0 j )
>>> complex ( 2 . 51 , 4 . 79 )
( 2 . 51+4 . 79 j )
>>> c1=4+5 j 
>>> c2=6+7 j
>>> complex(c1,c2)                                    # Equals ( 4+5 j ) + ( 6+7 j ) j = 4+5 j+6 j - 7 
( -3+11 j )
>>> c= ' 7 '
>>> complex (c)
( 7+0 j )
>>> c=' 7 + 4 j '
>>> complex (c)
( 7+4 j )
>>> x=2+3 j 
>>> x . real
2 . 0
>>> x . imag
3 . 0

delattr ( object , name )
This is a relative of setattr ( ). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it.

>>> class new__cls:
. . .                   def ______init_______ ( self , x ) :
. . .                   self. x=x
. . . 
>>> tt=new__cls ( 10 )
>>> tt . x
10 
>>> setattr ( tt ,' x ' , 20 )
>>> tt . x 
20
>>> setattr ( tt, ' y ' ' hello ' )
>>> tt.y 
' hello '
>>> delattr ( tt , ' x ' ) 
>>> tt . x 
Traceback ( most recent call last ) :
File "<stdin>", line 1 , in <module>
AttributeError: new__cls instance has no attribute ’ x ’

divmod ( a , b )
Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder.

>>> divmod ( 13 . 5 , 3 )
( 4 . 0 , 1 . 5 )
>>> divmod ( 13 , 3 )
( 4 , 1 )

enumerate ( sequence , start=0 )
Return an enumerate object. The sequence argument must be a sequence, an iterator, or some other object which supports iteration, while start is a count (default argument as 0).

>>> seasons=[ ' Spring ' , ' Summer ' , ' Fall ' , ' Winter ' ]
>>> list (enumerate ( seasons ) )
[ ( 0 ,' Spring ' ) , ( 1 , ' Summer ' ) , ( 2 , ' Fall ' ) , ( 3 , ' Winter ' ) ]
>>> list (enumerate ( seasons , start=2 ) )
[ ( 2 ,' Spring ' ) , ( 3 , ' Summer ' ) , ( 4 , ' Fall ' ) , ( 5 , ' Winter ' ) ] 
>>> for num , seasn in enumerate ( seasons , start=1 ) :
. . . print "[{0}] {1 } " . format ( num , seasn )
. . . 
[1] Spring
[2] Summer
[3] Fall
[4] Winter

filter ( function , iterable )
Create a list from those elements of iterable for which function returns True. The iterable may be either a sequence, a container that supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type, otherwise, it will be a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

>>> def isOdd ( x ) :
. . .               if ( x % 2 )==1: return True
. . .               else : return False
>>> filter ( isOdd, [88 , 43 , 65 ,-11 ,202 ] )
[ 43, 65, -11 ]
>>>
>>> def isLetter ( c ) : return c . isalpha ( )
. . . 
>>> filter ( isLetter,"01234abcdeFGHIJ* ( &!∧")
' abcdeFGHIJ '
>>> list= [ 0, 1, ( ) , (2, ) , 0 . 0, 0 . 25 ]
>>> filter ( None , list )
[1 , (2 ,), 0 . 25 ]
>>> filter ( boo1 , list )
[ 1 , ( 2 , ) , 0 . 25 ]

getattr ( object , name [ , default ] )
Return the value of the named attribute of the object; the name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. If the named attribute does not exist, default is returned if provided, otherwise, AttributeError is raised. For example, a complex number object has real and imag attributes.

>>> a=3 . 5 + 4 . 9 J 
>>> type ( a ) 
<type ' complex '>
>>> getattr ( a , ' real ' )
3 . 5
>>> getattr (a , ' imag ' )
4 . 9
>>> getattr ( a ,' imagine ' , 2 . 2 )
2 . 2

globals ( )
Return a dictionary representing the current global symbol table. The following script “GlobalScope.py” gives some idea about the use of this function.

# Filemame: GlobalScope . py 
var1=10 
def func (  ): 
var2=20 
func ( )
if ' var1 ' in globals ( ) . keys ( ) :
            print "'var1' is a global variable of this module" 
if 'var2' in globals ( ) . keys ( ) :
            print "'var2' is a global variable of this module"

The output is:

’ var1 ' is a global variable of this module

hasattr ( object , name )
The arguments are an object and a string. The result is True, if the string is the name of one of the object’s attributes, otherwise False.

>>> a=3.5+4.9 J
>>> hasattr( a , ' imag ' ) 
True 
>>> hasattr ( a,' imagine ' ) 
False

hash ( )
In computing, a hash table (also “hash map”) is a data structure that can map keys to values. A hash table uses a hash function to compute an index (or hash value) into an array of buckets or slots, from which the correct value can be found. The built-in function hash ( ) return the hash value of the object (if it has one) which is basically an integer and it never changes during its lifetime.

Hashability makes an object usable as a dictionary key and a set member because these data structures use the hash value internally. All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are hashable.

>>> d= { ' Lisa ' : 88 . 5 , ' John ' : 69 . 73 , ' Mike ' : 88 . 5 }
>>> hash ( d [ ' Lisa 1 ' ] )
1485012992
>>> hash ( d [ ' John ' ] )
-1664573625
>>> hash ( d [ ' Mike ' ] )
1485012992

Python Handwritten Notes Chapter 3 img 1

Consider the following example :

>>> map ( hash , ( " namea " , " nameb " , " namec " , " named " ) )
[-1658398457 , -1658398460 , -1658398459 , -1658398462 ]
>>> map ( hash , ( 0 , 1 , 2 , 3 ) )
[ 0 , 1 , 2 , 3 ]

It can be observed that the strings are quite close in their letters, and their hashes are close in terms of numerical distance which is desirable behavior. If the keys are close in nature, one wants their hashes to be close as well so that lookups remain fast. Integers have the same hash value as themselves.

help ( [ object ] )
This function invokes the built-in help system (this function is intended for interactive use). If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

>>> help (cmp)
Help on built-in function cmp in module ____builtin____ :
cmp ( . . . )
    cmp ( x , y ) -> integer

      Return negative if x<y , zero if x==y , positive if x>y .

hex ( x )
Convert an integer number (of any size) to a hexadecimal string. To obtain a hexadecimal string representation for a float, use the float. hex ( ) method.

>>> hex ( 25 )
' 0x19 '

id ( object )
Return the identity of the object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id ( ) value.

>>> a=5 
>>> id ( a )
3885104 
>>> b= ' hello '
>>> id ( b )
44148000

input ( [ prompt ] )
This function is used to take input from user and evaluates the expression. There is also raw_input ( ) function which takes input from user, convert it to a string, and returns that.

>>> aa=4 
>>> bb=6
>>> resultl=input( ' ----> ' )
- - - >aa+bb 
>>> result2=raw__input ( ' ---> ' )
----->aa+bb
>>>
>>> result1
10
>>> result2
' aa+bb ' 

isinstance ( object , classinfo )
Return True, if the object argument is an instance of the classinfo argument, or of a subclass thereof.

>>> class new__cls :
. . .        def _____init______ ( self , x ) : 
. . .              self . x=x 
. . . 
>>> tt=new_cls ( 10 )
>>> isinstance ( tt , new_cls )
True

Also return True, if classinfo is a type object, and an object is an object of that type or of a subclass thereof. If the object is not a class instance or an object of the given type, the function always returns False.

>>> i=5 
>>> type ( i )
<type ' int '>
>>> type ( int ) 
<type ' type ' >
>>> isinstance ( i , int )
True
>>> isinstance ( i , str )
False

If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, a TypeError exception is raised.

>>> isinstance( i ,( str , int , float , complex ) )
True

issubcTass ( class , classinfo )
Return True, if class is a subclass of classinfo.

>>> class A: 
. . .        pass
. . . 
class B(A):
. . .        pass
. . . 
>>> class C: 
. . .         pass
. . . 
>>> class D:
. . .        pass
. . . 
>>> issubclass ( B, A )
True

A class is considered a subclass of itself.

>>> issubclass ( D , D )
True

The classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.

>>> issubclass ( B , ( A , C , D ) )
True

len ( s )
Return the length (the number of items) of an object s. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

>>> len ( ' abed ' )
4
>>> seq=[ ' a ' , ' b ' , ' c ' , ' d ' ]
>>> len ( seq )
4
>>> seq= ( ' a ' , 'b \ 'c \ 'd')
>>> len ( seq )
4
>>> dict= { ' a ' : 8 , ' b ' :  9 , ' c ' : 10 , ' d ' : 11 }
>>> len ( diet )
4 '
>>> len ( ' ' )
0

locals ( )
The function returns a dictionary representing the current local symbol table.

# ! / usr / bin / env python 
# Filemame: LocalScope . py 
var1=10
var2=20 
    def func ( ) :
      var3=30 
       var4=40
print ' Local variables of func ( ) = ',locals ( ) 
func ( )
if 'var1' in locals ( ).keys ( ) and 'var2' in locals ( ) . keys( ) :
    print "'var1': and ' var2 ' are local variables of this module"

Output is:

Local variables of func( )= { ' var4 ' : 40 , ' var3 ' : 30 }
' var1 ' and ' var2 ' are local variables of this module

map ( function,iterable, . . . )
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, the function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another, it is assumed to be extended with None items.

If the function is None, the identity function is assumed; if there are multiple arguments, map ( ) returns a list consisting of tuples containing the corresponding items from all iterables. The iterable arguments may be a sequence or any iterable object; the result is always a list.

>>> def add100 ( x ) :
. . .        return x+100
. . .
>>> map ( add100 , ( 44 , 22 , 66 ) )
[ 144 , 122 , 166 ]
>>>
>>> def abc ( a , b , c ) :
. . .        return a*10000+b*100+c
. . . 
>>> map ( abc , ( 1 , 2 , 3 ) , ( 4 , 5 , 6 ) , ( 7 , 8 , 9 ) )
[ 10407 , 20508 , 30609 ]
>>>
>>> map ( None , range ( 3 ) )
[ 0 , 1 , 2 ]
>>> map (None,range ( 3 ) , ' abc ' , [ 44 , 55 , 66 ] )
[ ( 0 , ' a ' , 44 ) , ( 1, -b ’ , 55 ) , ( 2 , *c ', 66 ) ]

max ( iterable [ , key ] )
Return the largest item in an iterable. The optional argument key specifies a function of one argument that is used to extract a comparison key from each list element. The default value is None (compare the elements directly),

>>> max ( ' hello ' )
' o '
>>> max ( [10, 80, 90, 20,-100] )
90 
>>> def LessThanFifty ( x ) :
. . .         if x<=50 :
. . .          return x
>>> max ( [ 10 , 80 , 90 , 20 , -100 ] , key=LessThanFifty )
20

The function has another form max (arg1, arg2, *args [, key] ), which returns the largest of two or more arguments.

>>> max ( ' hi ' ,  ' hello ' ,  ' bye ' ) 
' hi '
>>> max ( ' Gumby ' , ' Lambert ' , ' Sartre ' , ' Cheddar ' )
' Cheddar '
>>> max ( ' Gumby ' , ' Lambert ' , ' Sartre ' , ' Cheddar ' , key=str.upper )
' Sartre '

min ( iterable [ , key ] )
Return the smallest item in an iterable. The key has same meaning as that in max ( ) function.

>>> min ( ' hello' )
' e '
>>> min ( ( 10 , 80 , 90 , 20 , -100 } )
-100

The function has another form min (arg1, arg2, *args [ , key] ), which returns the smallest of two or more arguments.

>>> min ( 10 , 80 , 90 , 20 , -100 )
-100
>>> def rev ( x ) : return -x
. . . 
>>> min ( 10 , 80 , 90 , 20 , -100 , key=rev )
90

next ( iterator [ , defauIt ] )
Retrieve the next item from the iterator. If the default is given, it is returned if the iterator is exhausted, otherwise, Stoplteration is raised.

>>> it=iter ( xrange ( 0 , 3 ) )
>>> next ( it , ' Done ' )
0
>>> next ( it , ' Done ' )
1
>>> next ( it ,  'Done ' ) 
2 
>>> next ( it , ' Done ' ) 
' Done '
>>> next ( it , ' Done ' )
' Done ' 
>>> it=iter ( xrange ( 0 , 3 ) )
>>> next ( it )
0
>>> next ( it )
1 
>>> next ( it )
2
>>> next ( it ) 
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
Stoplteration

oct ( x )
Convert an integer number (of any size) to an octal string.

>>> oct ( 135 )
' 0207 '

pow ( x , y [ , z ] )
Return x to the power y; if z is present, return x to the power y, and modulo z (computed more efficiently than pow (x, y) %z). The two-argument form pow (x, y) is equivalent to using the power operator x* *y. The arguments must be of numeric types. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative.

>>> 2 * * 4 
16
>>> pow ( 2 , 4 )
16
>>> ( 2 * * 4 ) % 3 
1
>>> pow ( 2 , 4 ,3 )
1

print ( * objects , sep=’ ‘ , end=’ \ n ‘ , file=sys . stdout )
Print objects to the stream file, separated by sep and followed by end. If sep, end and file, are present, they must be given as keyword arguments. All non-keyword arguments are converted to strings and written to the stream, separated by sep and followed by end. Both sep and end must be strings, they can also be None, which means to use the default values. If no objects are given, print ( ) will just write end. The file argument must be an object with a write ( ) method, if it is not present or None, sys. stdout (file objects corresponding to the interpreter’s standard output stream) will be used.

This function is not normally available as a built-in function, since the name print is recognized as the print statement. To disable the statement and use the print ( ) function, use the following future statement before using the function.

>>> from _____future______ import print_function
>>> x , y=3 , 5
>>> print ( ' The sum of ' , x , ' plus ' , y , ' is ' , x+y )
The sum of 3 plus 5 is 8
>>> print ( ' The sum of ' , x , ' plus ' , y , ' is ' , x+y , sep =' ' )
The sum of 3 plus 5 is 8
>>> print ( ' The sum of ' , x , ' plus ' , y , ' is ' , x+y , sep='  ' , end=' \ n The \ n End \ n ' )
The sum of 3 plus 5 is 8
The 
End

range( start,stop[,step] )
This function creates list whose elements are in arithmetic progression. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. step must not be zero (or else ValueError is raised).

>>> range ( 10 )
[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
>>> range ( 1 , 11 ) 
[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
>>> range ( 0 , 30 , 5 ) 
[ 0 , 5 , 10 , 15 , 20 , 25 ]
>>> range ( 0 , 10 , 3 ) 
[ 0 , 3 , 6 , 9 ] 
>>> range ( 0 , -10 , -1 ) 
[ 0 , -1 , -2 , -3 , -4 , -5 , -6 , -7 , -8 , -9 , ]
>>> range ( 0 )
[ ]
>>> range ( 10 , 5 )
[ ]
>>> range ( 10 , 5 , -1 )
[ 10 , 9 , 8 , 7 , 6 ]

reload ( module )
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if the programmer has edited the module’s source file using an external editor and wants to try out the new version without leaving the Python interpreter. The return value is the module object.

reversed ( seq )
The function returns an iterator object that can iterate over all the objects in the container in reverse order.

>>> Seq= [ 10, 20, 30 ]
>>> revSeq=reversed ( Seq ) 
>>> for item in revSeq: print item
. . . 
30 
20
10

round ( number [ , ndigits ] )
Return the floating-point value number rounded to digits after the decimal point. If digits are omitted, it defaults to zero.

>>> round ( 2 .769753 )
3 . 0
>>> round ( -2 . 769753 )
-3 . 0 
>>> round ( 2 . 769753 , 4 )
2 . 7698
>>> round ( -2 . 769753 , 4 )
-2 . 7698

setattr ( object, name, value )
This is the counterpart of getattr ( ). The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. The following example will become clearer after going through chapter 6.

>>> class new_cls:
. . .             def init ( self , x ) :
. . .           self . x=x
>>> tt=new_cls ( 10 )
>>> tt.x 
10
>>> setattr ( tt , ' x ' , 20 )
>>> tt.x 
20
>>> setattr ( tt , ' yhello ' )
>>> tt.y 
' hello '

slice ( start , stop [ , step ] )
Return a slice object representing the set of indices specified by range (start, stop, step). The function can also be of form slice (stop), where the start and step arguments default to None. Slice objects have read-only data attributes start, stop, and step, which merely returns the argument values (or their default).

>>> slice ( 20 ) 
slice ( None , 20 , None )
>>> s1=slice ( 2 , 20 , 3 ) 
>>> type ( s1 ) 
<type ' slice ' >
>>> s1 . start 
2 
>>> s1 . stop 
20
>>> s1 . step 
3

The slice object can be passed to the ________getitem__________ ( ) method of the built-in sequences.

>>> range ( 50 ). getitem ( s1 )
[ 2 , 5 , 8 , 11 , 14 , 17 ]

Or use slice objects directly in subscripts:

>>> range ( 50 ) [ s1 ]
[ 2 , 5 , 8 , 11 , 14 , 17 ]

sorted ( iterable [ , cmp [ , key [ , reverse] ] ] )
Return a new sorted list from the items in iterable. The arguments cmp, key, and reverse are optional.

>>> a= [ 66 . 25 , 333 , ' abc ' , 333 , 1 , ’ ab ' , 1234 . 5 ]
>>> sorted ( a )
[ 1 , 66 . 25 , 333 , 333 , 1234 . 5 , ' ab ' , ' abc ' ]
>>> sorted ( { 10 : ' D ' , 5 : ' B ' , 8 : ' B ' , 6 : ' E ' , 2 : ' A ' } )
[ 2 , 5 , 6 , 8 , 10 ]

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. The default value is None.

key specifies a function of one argument that is used to extract a comparison key from each list element. The default value is None (compare the elements directly).

>>> strs= [ ' ccc ' , ' aaaa ' , ' d ' , ' bb ' ]
>>> sorted ( strs , key=len)                               # Sorted by string length
[ ' d ' , ' bb ' , ' ccc ' , 'aaaa ' ]
>>> student_tuples=[
. . . ( ' john ' , ' A ' , 15 ) ,
. . . ( ' jane ' , ' B ' , 12 ) ,
. . . ( ' dave ' , ' B ' , 10 ) , ]
>>> sorted ( student_tuples , key=lambda student : student [ 2 ] )                        # By age 
[ ( ' dave ' , ' B ' , 10 ) , ( ' jane ' , ' B ' , 12 ) , ( ' john ' , ' A ' , 15 ) ]

the reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

>>> a= [ 66 . 25 , 333 , ' abc ' , 333 , 1 , ' ab ' , 1234 . 5 ]
>>> sorted ( a , reverse = True )
[ ' abc ' , ' ab ' , 1234 . 5 , 333 , 333 , 66 . 25 , 1 ]

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element, while key and reverse touch each element only once.

>>> L= [ ' geas ' , ' clue ' , ' Zoe ' , ' Ann ' ]
>>> sorted ( L )
[ ' Ann ' , ' Zoe ' , ' clue ' , ' geas ' ]
>>> def ignoreCase(x,y) :
. . . return cmp ( x . upper ( ) , y . upper ( ) ) 
. . . 
>>> sorted ( L , ignoreCase )
[ ' Ann ' , ' clue ' , ' geas ' , ' Zoe ' ]
>>> sorted ( L , None , str . upper )
[ ' Ann ' , ’ clue ' , ' geas ' , ’ Zoe ' ]
>>> L
[ ' geas ' , ' clue ' , ' Zoe ' , ' Ann ' ] 

sum ( iterable [ , start ] )
The function returns the sum total of start ( defaults to 0 ) and the items of an iterable.

>>> seq= [ 5 , 7 . 4 , 2 , 11 ]
>>> sum ( seq )
25 . 4
>>> sum ( seq , 10 . 2 )
35 . 6
>>> aa=4
>>> bb=2 . 5
>>> cc=9 . 1
>>> seq= [ aa , bb , cc ]
>>> sum ( seq )
15 . 6

type ( object )
The function returns the type of an object.

>>> i=50 . 7 
>>> type ( i )
<type ' float '>
>>> type ( i ) is float 
True

xrange ( start , stop [ , step ] )
This function is very similar to range ( ), but returns an xrange object instead of a list. This yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange ( ) over range ( ) is minimal, except when a very large range is used on a memory-starved machine or when all of the range ( ) elements are never used (such as when the loop is usually terminated with break). The function can also be used as xrange (stop).

The xrange type is an immutable sequence that is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages. The xrange objects support indexing, iteration, and the len ( ) function.

>>> for i in xrange ( 2000000000 ) :
. . . print i
. . . if i > 5 :
. . . break 
. . . 
0
1
2
3
4
5
6
>>> for i in range ( 2000000000 ) :
. . . print i
. . . if i>5 :
. . . break
. . .
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
MemoryError

zip ( [ iterable , . . . ] )
This function returns a list of tuples, where the /th tuple contains the /th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments that are all of the same lengths, zip ( ) is similar to map ( ) with an initial argument of None. With no arguments, it returns an empty list, zip ( ) in conjunction with the * operator can be used to unzip a list:

>>> x= [ 1 , 2 , 3 ]
>>> y=[ 4 , 5 , 6 , 7 , 8 ]
>>> zipped=zip ( x , y )
>>> zipped
[ ( 1 , -4 ) , ( 2 , 5 ) , ( 3 , 6 ) ]
>>> zip ( x )
[ ( 1 , ) , ( 2 , ) , ( 3 , ) ]
>>> x2 , y2=zip ( *zipped )
>>> x2 
( 1 , 2 , 3 )
>>> y2 
( 4 , 5 , 6 )
>>> zip ( ) 
[ ]

Python Programming – Compound statement Built-in functions Read More »

Python: if-else in One Line/Ternary Operator in Python

How to write an if-else statement in one line in python

In this article, we will discuss how we can implement the if-else statement in python in a single line. This is also called the ternary operator. In python, the ternary operator doesn’t have syntax like that in c++ or java but working is the same. Let us see this concept with some examples.

Syntax: val1 if [expression] else val2

Explanation: If our if the statement becomes true then we get output as val1 otherwise we get output as val2.Let us see this with an example.

a=10
print(1 if a%2==0 else 0)
a=9
print(1 if a%2==0 else 0)

Output

1
0

Here we see that we get output 1 when our number is even else we get output as 0. When the condition evaluates to True, then the result of this one-liner if..else expression will be val1 in this case 1. Whereas, if the condition evaluates to False, then the result of this one-liner expression will be val2 in this case 0.

Here we use integer with our if-else statement. Let us see an example of how to deal with a string.

a=10
print("Number is even" if a%2==0 else "Number is odd")

Output

Number is even

Here we see that how we easily deal with string with this ternary operator or one-liner if-else statement. In a similar way, we can deal with different data types.

With the increase in the simplicity of code, we also have to take some precaution otherwise a situation may arise in which we understand the code in a different way while the code work in a different way. As different operator have different associativity and precedence which increase the responsibility of the programmer to use this operator in a correct way. Let us understand the concept with help of an example.

a=10 
b=5
print(a/b*3 if a%2==0 else 1)
print(a/(b*3 if a%2==0 else 1))

Output

6.0
0.6666666666666666

Here we see with change in one bracket our output differ but code seems to be similar.This confusion tend to be increase when we write big and complex code.Hence we have to use operator in a proper way.

Note: Conditional expressions have the lowest priority amongst all Python operations.

Nested if-else in one line

We see that we can execute single if-else in a single line easily.Now we see how we can execute multiple if else statement in a single line with the help of an example.

a=10 
print("a is negative" if a<0 else "a is positive" if a>0 else "a is 0")

#above code is similar as
if(a<0):
    print("a is negative")
else:
    if(a>0):
        print("a is positive")
    else:
        print("a is 0")

Output

a is positive
a is positive

Both the code give a similar result. We see how we save 5-6 lines by using the ternary operator.

So in this article, we see how to use the if-else and nested if-else statement in one line and with that, we see how to use the operator effectively otherwise the result may differ.

Python: if-else in One Line/Ternary Operator in Python Read More »

Python : Join / Merge Two or More Lists

Basic Concepts/Terminologies

In this article, we will discuss different ways to join two or more lists in python. Before going to the actual let us understand about lists in python.

List

The list is one of the data structures in python that is used to store multiple items in a single variable. The best thing about the list is that we can store the value of different data types in a single list i.e. we can store string, int, and float values in the same list.

l=[1,2,"list",3.3,"Raj",4]
print(type(l))

Output

<class 'list'>

In this example, we see how we can easily store different variables in the same list.

Ways to join two or more lists in python

  • Method 1-Using the “+” operator

Here the role of the “+” operator is the same as in maths. The “+” operator can easily join/merge two or more lists like we add two or more numbers in maths. In python, we called this concept concatenation. Let us see this concept with the help of an example.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
new_l=l1+l2
print(new_l)

Output

[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']

Here we see that how we easily concatenate our lists using the “+” operator. The second thing to notice here is that the list that comes before the “+” operator has also come before another list in the new list.

  • Method 2-Using for loop

This is also one of the methods to merge two or more lists in python. In this method, we iterate through all the elements in one list and append these elements in the second list. Fore appending element in the second list we can use the append() method which is an inbuilt method in a python list. Let us see this method with the help of an example.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
for item in l1:
    l2.append(item)
print(l2)

Output

[8, 1.1, 'list2', 1, 2, 'list1', 3.3, 'Raj', 4]
  • Method 3-Using list.extend()

extend() method is used to add all the elements of an iterable i.e. list, tuple, etc at the end of the list. The best thing about this method is that we don’t need to use it for loops. we simply pass our iterable as an argument in extend() function and our task will be done. This is an in-place method that means it made changes in an existing list instead of creating a new list.

syntax: list.extend(anotherList)

Let us see this method with the help of an example.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
l1.extend(l2)
print(l1)

Output

[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']
  • Method 4-Using list comprehensions

Before understanding this method let us take a quick look at what list comprehension is.

List comprehensions

List comprehension is a way of creating a new list from the existing list. It helps in solving the problem related to list in one line.

Let us see how to join two lists using list comprehension with the help of an example.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
l = [y for x in [l1, l2] for y in x]
print(l)

Output

[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']

Here we how we easily join our two lists using list comprehension.

  • Method 5- Using itertools.chain()

Before understanding this method let us see what an itertools is.

itertools

It is a module in python that provides methods to work flexibly with different iterables in python. To use this module we have to import this using the import keyword in our program.

itertools.chain()

This method takes multiple iterables at a one-time group them and produces a single iterable as output.

syntax-itertools.chain(*iterables)

Here * indicates that we can pass multiple iterable as a parameter in this function.

Let us see this concept with the help of an example.

import itertools
l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
l=itertools.chain(l1, l2)
merge_list=list(l)
print(l)
print(merge_list)

Output

<itertools.chain object at 0x000002A9837445F8>
[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']

Explanation

This method returns a chain object as we see in the output. We convert this chain object to a list to get our desired output.

  • Method 6- Using unpacking or “*” operator

As the name suggests unpacking or “*:” is used to unpack the content of any iterables object. Hence we can unpack the content of two or more lists and then merge them to form a new list.

Note: This method works only in python3.6+ versions.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
l = [*l1, *l2]
print(l)

Output

[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']

So these are the methods to append two or more lists in python.

Python : Join / Merge Two or More Lists Read More »

Python : Sort a List of Numbers in Ascending or Descending Order | list.sort() vs sorted()

A list is used in Python to store the sequence of different types of data. Python lists are mutable, which means that their elements can be changed after they have been created. Python, on the other hand, has six data types that can be used to store sequences, with the first two on the list being the most common and accurate.

A list is a collection of various types of values or objects. The list items are separated by a comma (,), which is enclosed in square brackets [].

Example:

Input:

givenlist = [3, 5, 1, 6, 9, 2, 8, 7]

Output:

Ascending order:

[1, 2, 3, 5, 6, 7, 8, 9]

Descending order:

[9, 8, 7, 6, 5, 3, 2, 1]

Sort the given list

In this article, we’ll look at two methods for sorting a list of numbers in ascending and descending order.

Method #1: Using sort() function to sort in ascending order:

It’s a built-in function that takes an iterable and returns a new sorted list from it.
Note:

  •  sort is a list class method that can only be used with lists. It is not a built-in that has been passed an iterable.
  • sort() returns None and modifies the existing values. Let’s look at the effects of both of these code differences.

Let us the sort the list of integers in ascending order

Below is the implementation:

# Driver code
# Given list
givenlist = [3, 5, 1, 6, 9, 2, 8, 7]
# sorting the given list in ascending order
givenlist.sort()
print(givenlist)

Output:

[1, 2, 3, 5, 6, 7, 8, 9]

Method #2: Using sort() function to sort in descending order:

Using reverse=True gives the list in descending order

Below is the implementation:

# Driver code
# Given list
givenlist = [3, 5, 1, 6, 9, 2, 8, 7]
# sorting the given list in descending order
givenlist.sort(reverse=True)
print(givenlist)

Output:

[9, 8, 7, 6, 5, 3, 2, 1]

Method #3: Using sorted() function to sort in ascending order

The sorted() function returns a sorted list of the iterable object specified. You can specify whether the order should be ascending or descending. Numbers are sorted numerically, while strings are sorted alphabetically. It is important to note that you cannot sort a list that contains BOTH string and numeric values.

Characteristics of sorted() function:

  • It was not necessary to define the function sorted(). It is a built-in function that is available in a standard Python installation.
  • With no additional arguments or parameters, sorted() orders the values in numbers in ascending order, from smallest to largest.
  • Because sorted() returns sorted results and does not change the original value in place, the original numbers variable remains unchanged.
  • When sorted() is invoked, it returns an ordered list as a result.

Below is the implemenation:

# Driver code
# Given list
givenlist = [3, 5, 1, 6, 9, 2, 8, 7]

# using sorted function to sort the given list in ascending order
newlist = sorted(givenlist)
# printing the newlist
print(newlist)

Output:

[1, 2, 3, 5, 6, 7, 8, 9]

Method #4: Using sorted() function to sort in descending order:

Using reverse=True gives the list in descending order

Below is the implementation:

# Driver code
# Given list
givenlist = [3, 5, 1, 6, 9, 2, 8, 7]

# using sorted function to sort the given list in descending order using reverse=True
newlist = sorted(givenlist, reverse=True)
# printing the newlist
print(newlist)

Output:

[9, 8, 7, 6, 5, 3, 2, 1]

 

Related Programs:

Python : Sort a List of Numbers in Ascending or Descending Order | list.sort() vs sorted() Read More »

Python How to Remove Multiple Elements from List

Python : How to Remove Multiple Elements from List ?

In Python, a list is used to store the sequence of different types of data. Python lists are mutable, which means we can change their elements after they’ve been formed. However, Python has six data types that can be used to store sequences, with the list being the most common and accurate.

A list can be described as a set of different types of values or objects. The comma (,) separates the things in the list, which are enclosed in square brackets [].

Remove multiple items from the list

The following is a list of possible python methods to remove multiple elements from the list:

Method #1:Using remove() function while iterating through the list

The remove() method removes the first matching element from the list (which is passed as an argument).

remove() parameters:

  • The remove() method accepts a single argument and removes it from the list.
  • If the element does not exist, a ValueError: list.remove(x): x not in list exception is thrown.

Let us remove all elements which are divisible by 2.

Traverse the list and remove the element if it is divisible by 2.

Below is the implementation:

# function which remove multiple items from the list
def removeMultiple(givenlist):
    # Traverse the list
    for element in list(givenlist):
        # Checking the given condition
        if(element % 2 == 0):
            # remove the element from the given list
            givenlist.remove(element)
    # return the given list
    return(givenlist)


# Driver code
# Given list
givenlist = [1, 2, 3, 4, 5, 6, 7, 8]
# passing the list to removeMultiple function
print(removeMultiple(givenlist))

Output:

[1, 3, 5, 7]

Method #2:Using del keyword and slicing

Another way to delete an element from a list is to use its index in the del statement. It differs from the pop() function in that it does not return the removed element. Unlike the slicing feature, this does not generate a new list.

If we want to remove multiple elements from a list based on an index range, we can use the del keyword.

Suppose we want to delete elements from 2 to 5 indices we can use slicing and del keyword to do that.

It will remove the elements from index1 to index2 – 1 from the list.

Below is the implementation:

# function which remove multiple items from the list
def removeMultiple(givenlist):
    # using del keyword and removing indices from 2 to 5
    # increment the right index with 1 to remove it
    del givenlist[2:6]
    # return the given list
    return(givenlist)


# Driver code
# Given list
givenlist = [1, 2, 3, 4, 5, 6, 7, 8]
# passing the list to removeMultiple function
print(removeMultiple(givenlist))

Output:

[1, 2, 7, 8]

Method #3: Using List Comprehension

Python’s syntax for deriving one list from another is concise. These expressions are known as list comprehensions. Python list comprehensions make it extremely simple to apply a function or filter to a list of items. List comprehensions can be very useful when used correctly, but they can also be very unreadable if used incorrectly.

Let us remove all elements which are divisible by 2.

We can achieve that easily by list comprehension as given below:

# function which remove multiple items from the list
def removeMultiple(givenlist):
    # using list comprehension
    givenlist = [element for element in givenlist if element % 2 != 0]
    # return the given list
    return(givenlist)


# Driver code
# Given list
givenlist = [1, 2, 3, 4, 5, 6, 7, 8]
# passing the list to removeMultiple function
print(removeMultiple(givenlist))

Output:

[1, 3, 5, 7]

Related Programs:

Python : How to Remove Multiple Elements from List ? Read More »

Python: How to Convert Integer to String

Integer:

An integer, on the other hand, is a whole number, the kind you started counting out in school when you first heard about numbers. In Python 3, an integer can be any length up to the computer’s memory limit, so you’ll probably never run out of integers to use.

String:

In computer programming, a string is a sequence of characters that can be used as a literal constant or as a variable. A string is a finite sequence of symbols chosen from an alphabet in formal languages, which are used in mathematical logic and theoretical computer science.

Example:

Input:

IntegerValue=23

Output:

StringValue: 23
Type : <class 'str'>

Integer to String conversion

The following is a list of possible python methods for converting an integer to a string:

Method #1: Using str() function

The str() function in Python can be used to convert an integer to a string. Any python data type can be passed to the str() function, which converts it to a string.

The str() function converts an object to a string. An int, char, or string may be used as the object. It returns an empty string if the object is not passed as an argument.

Below is the implementation:

# given integer
intvalue = 23
# converting to string using str() function
strvalue = str(intvalue)
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Method #2: Using “%s” keyword

This is the most traditional method. We may insert objects within a string using positional formatting.

Below is the implementation:

# given integer
intvalue = 23
# converting to string using str() function
strvalue = "%s" % intvalue
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Method #3:Using format() function

Python’s string class has a format() feature. It converts the string by substituting the values of the variables for the placeholders specified within.

Below is the implementation:

# given integer
intvalue = 23
# converting to string using format() function
strvalue = "{}".format(intvalue)
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Method #4: Using f-strings

F-strings allow you to use a simple syntax to insert expressions within string literals. It’s worth noting that an f-string is actually an expression that is evaluated at runtime rather than a fixed value. An f-string is a literal string in Python source code that includes expressions within braces and is prefixed with ‘f’. The values are substituted for the expressions.

Below is the implementation:

# given integer
intvalue = 23
# converting to string using f-strings
strvalue = f'{intvalue}'
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Method #5: Using __str__()

Internally, the str(object) function calls __str__() on the passed argument object. As a result, we may use the object’s __str__() method directly. In the previous example, we passed an integer to the str() function. Instead, we can use the int object’s __str__() function to get a string representation of the integer.

# given integer
intvalue = 23
# converting to string using __str__
strvalue = intvalue.__str__()
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Related Programs:

Python: How to Convert Integer to String Read More »

Python: Remove First Element from a List

A list is used in Python to store the sequence of different types of data. Python lists are mutable, which means that their elements can be changed after they have been created. Python, on the other hand, has six data types that can be used to store sequences, with the first two on the list being the most common and accurate.

A list is a collection of various types of values or objects. The list items are separated by a comma (,), which is enclosed in square brackets [].

Examples:

Input:

givenlist = ["Hello", "Btech" , "Geeks" ,"is" ,"new" ,"online" ]

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

Explanation:

Hello is the first element in givenlist hence it is deleted.

Remove the First Element of a List

There are several ways to remove the first item from the list some of them are:

>Method #1:Using slicing

Lists can be cut in Python, as we all know. Slicing is a method of removing the first item from a list. The goal is to make a sublist that contains all of the elements of the list except the first one. Because the slice operation returns a new list, we must assign the new list to the original list. To accomplish this, use the expression l = l[1:], where l is your list. l[1:] is an abbreviation for l[0:len(l)-1].

Below is the implementation:

# Function which removes first element
def removeFirstElement(givenlist):
    # using slicing
    givenlist = givenlist[1:]
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

>Method #2:Using del keyword

Another way to delete an element from a list is to use its index in the del statement. It differs from the pop() function in that it does not return the removed element. Unlike the slicing feature, this does not generate a new list.

The index of first item in list is 0.

Below is the implementation:

# Function which removes first element
def removeFirstElement(givenlist):
    # using del keyword
    del givenlist[0]
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

>Method #3:Using pop() function

The list class in Python has a function called pop(index), which takes an optional argument index and deletes the element at that index. If no justification is given, it deletes the last element of the list by default.

The index of first element in list is 0.

Below is the implementation:

# Function which removes first element
def removeFirstElement(givenlist):
    # using pop function
    givenlist.pop(0)
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

>Method #4:Using remove() function

The list class in Python has a function remove(value) that deletes the first occurrence of a given value from the list. This can be used to remove the first item from the list. Select the first element from the list and pass it to the remove() function to accomplish this.

Below is the implementation:

# Function which removes first element
def removeFirstElement(givenlist):
    # getting first element of the given list
    firstelement = givenlist[0]
    # using remove function
    givenlist.remove(firstelement)
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

>Method #5:Using deque() function

A double-ended queue, or deque, allows you to add and remove elements from either end. The Deque module is a collection library module. It has methods for adding and removing elements that can be directly invoked with arguments.

Convert the given list to a deque and then pop an element from the left. Then add the remaining deque elements to the list.

Below is the implementation:

from collections import deque
# Function which removes first element


def removeFirstElement(givenlist):
    # converting given list to deque
    dequelist = deque(givenlist)
    # using popleft function to remove first element
    dequelist.popleft()
    # Converting deque to list
    givenlist = list(dequelist)
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

Related Programs:

Python: Remove First Element from a List Read More »

Python : Convert List of Lists or Nested List to Flat List

Lists are similar to dynamically sized arrays declared in other languages (for example, vector in C++ and ArrayList in Java). Lists do not always have to be homogeneous, which makes it a very useful tool in Python. A single list can contain DataTypes such as Integers, Strings, and Objects. Lists are mutable, which means they can be modified after they are created.

A list of lists is a list object in Python, with each list element being a separate list.

Example:

Input:

listoflists = [ [3 ,6 ,7 ] , [1 , 2, 3 ] , [8 , 7, 6 ] ]

Output:

[3, 6, 7, 1, 2, 3, 8, 7, 6]

Nested Lists to Flat list Conversion

There are several ways to convert nested list to flat list some of them are:

Method#1:Using extend() function

Extend in Python:

The extend() method appends to the end of a list all the elements of an iterable (list, tuple, string, etc.). All iterable elements are added to the end of list1 in this case.

It adds all the contents of the given iterable to the existing list object. Let’s put this to use and convert a list of lists to a flat list.

Approach:

  • Take a empty list say flatlist
  • Traverse the given list of lists, and for each list within it, extend that list to flatlist.
  • print flatlist

Below is the implementation:

# Function to convert list of lists to flat list
def convertToFlatList(listoflists):
    # Taking empty flat list
    FlatList = []
    # Traverse the given listoflists
    for element in listoflists:
        # Adding this list to flatlist using extend
        FlatList.extend(element)

        # returning the flatlist
    return FlatList


# Driver code
# given listoflists
listoflists = [[3, 6, 7], [1, 2, 3], [8, 7, 6]]
# passing listoflists to convertToFlatList function
print(convertToFlatList(listoflists))

Output:

[3, 6, 7, 1, 2, 3, 8, 7, 6]

Method #2:Using append() function

Append():

Python’s append() method adds a single item to an existing list. It does not return a new list of items, but rather modifies the original list by appending the item to the end. The size of the list increases by one after executing the method append on it.

Approach:

  • Take a empty list say flatlist
  • Traverse the given list of lists, and then traverse it again using a loop for each list within it, appending all the elements to flatlist.
  • print flatlist.

Below is the implementation:

# Function to convert list of lists to flat list
def convertToFlatList(listoflists):
    # Taking empty flat list
    FlatList = []
    # Traverse the given listoflists
    for element in listoflists:
        # Traverse the inner list
        for loopelement in element:
          # appeend this loopelement
            FlatList.append(loopelement)

        # returning the flatlist
    return FlatList


# Driver code
# given listoflists
listoflists = [[3, 6, 7], [1, 2, 3], [8, 7, 6]]
# passing listoflists to convertToFlatList function
print(convertToFlatList(listoflists))

Output:

[3, 6, 7, 1, 2, 3, 8, 7, 6]

Method #3:Using List Comprehension

We’ll use list comprehension to iterate over a list of lists, then iterate over the individual elements in each internal list. Then, in a new list, add those elements.

Below is the implementation:

# Function to convert list of lists to flat list
def convertToFlatList(listoflists):
    # Using list Comprehension
    FlatList = [item for element in listoflists for item in element]

    # returning the flatlist
    return FlatList


# Driver code
# given listoflists
listoflists = [[3, 6, 7], [1, 2, 3], [8, 7, 6]]
# passing listoflists to convertToFlatList function
print(convertToFlatList(listoflists))

Output:

[3, 6, 7, 1, 2, 3, 8, 7, 6]

Related Programs:

Python : Convert List of Lists or Nested List to Flat List Read More »

Python: Dictionary with Multiple Values per Key

How we can create a dictionary with multiple values per key in python.

In python a dictionary is one of the important datatype which is used to store data values in key : value pair. Generally keys and values are mapped one-to-one. But it is not impossible that we can not map multiple values to a single key. So in this article we will discuss how we can map multiple values per key in dictionary.

Syntax of dictionary :

dictionary_name = {key1: value1, key2: value2}

where,

  • key1, key2… represents keys in a dictionary. These keys can be a string, integer, tuple, etc. But keys needs to be unique.
  • value1, value2… represents values in dictionary. These values can be numbers, strings, list or list within a list etc.
  • key and value is separated by : symbol.
  • key-value pair symbol is separated by , symbol.

Example of a dictionary covid_case where multiple values are associated with single key.

covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }

So, now let’s explore the concept how to add a key:value pair to dictionary in Python.

Create a dictionary with a list as the value :

Generally, when multiple values are mapped to a single key, then that dictionary is called as MultiDict. So, let’s see an example how in dictionary multiple values are mapped to a single key.

#Program :

#Multiple values mapped to single key
covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
#printing the multidict
print("Dictionary with multiple values per key :")
print(covid_case)
Output :
Dictionary with multiple values per key :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }

In this example string keys have taken in a dictionary where multiple integer values are mapped to single key.

Finding multiple values of a key in the dictionary :

Like how we created a dictionary with a list as a value, similar we can get a list as output also. Means it is possible to get multiple values of a key in dictionary. So, let’s see an example how we can get multiple values of a key as a list.

#Program :

#Multiple values mapped to single key
covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
#printing the multidict
print("Complete dictionary :")
print(covid_case)
#Getting the list(multiple values) at key February
output_list=covid_case["February"]
#printing the multiple values of key February
print("Multiple values of key 'February' :")
print(output_list)
Output :
Complete dictionary :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
Multiple values of key 'February' :
[1100,1300,1500]

Append multiple values to a key in a dictionary :

It is easy to create a dictionary where multiple values are mapped to a single key. But the tricky part is appending multiple values where already multiple values are mapped to that key.

So there 2 cases may arise i.e

  1. The key is already present with multiple values and new values will be added in that key.
  2. The key is not present in the dictionary, so new key with multiple values will be appended to that dictionary.

CASE -1 : Key is already present in dictionary :

#Program :

#Multiple values mapped to single key
covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
#printing the multidict
print("Before append :")
print(covid_case)


# Append multiple values to a key in dictionary covid_case 
def add_values_to_key(temp_dict, key, list_of_values):
    if key not in temp_dict:
        temp_dict[key] = list()
    temp_dict[key].extend(list_of_values)
    return temp_dict
    
    
# Append multiple values for existing key 'March'
covid_case = add_values_to_key(covid_case, 'March', [2600, 2800])
#printing the multidict
print("After append :")
print(covid_case)
Output :
Before append :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
After append :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400,2600,2800] }

CASE -2 : Key is not present in dictionary :

#Program :

#Multiple values mapped to single key
covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
#printing the multidict
print("Before append :")
print(covid_case)


# Append multiple values to a key in dictionary covid_case 
def add_values_to_key(temp_dict, key, list_of_values):
    if key not in temp_dict:
        temp_dict[key] = list()
    temp_dict[key].extend(list_of_values)
    return temp_dict
    
    
# Append multiple values for key 'April'
#As key 'April' is not present so new key with multiple values will be added
covid_case = add_values_to_key(covid_case, 'April', [3000, 3500])
#printing the multidict
print("after append :")
print(covid_case)
Output :
Before append :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
After append :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400], "April":[3000,3500 }

Python: Dictionary with Multiple Values per Key Read More »