Collection or List in Python Programming

Collection or List in Python Programming

A collection or list allows us to store multiple values in a variable.

for and in statements can be used to iterate a list in Python programming.

Example:

fruits = [ 'Apple', 'Banana', 'Grapes' ];
for fruit in fruits :
    print ( fruit );

Lists in Python programming are mutable. So, we can change the value using index operator.

Example:

fruits = [ 'Apple', 'Banana', 'Grapes' ];
for fruit in fruits :
    print ( fruit );
#Changing Grapes to Orange
fruits[ 2 ] = 'Organge';
for fruit in fruits :
    print ( fruit );

len() can be used to find the number of items in the list.

Example:

fruits = [ 'Apple', 'Banana', 'Grapes' ];
print ( len( fruits ) );

range() can be used with len() to find the index range of the list.

Example:

fruits = [ 'Apple', 'Banana', 'Grapes' ];
print ( range( len( fruits ) ) );

list() is used to initialize a list variable and append() is used to add values to the list variable in Python programming.

Example:

fruits = list();
fruits.append(  'Apple' );
fruits.append(  'Banana' );
fruits.append(  'Grapes' );
print ( fruits );

sort() can be used to sort the list in Python programming.

Example:

fruits = list();
fruits.append(  'Grapes' );
fruits.append(  'Banana' );
fruits.append(  'Apple' );
print( 'Before Sorting' );
print ( fruits );
fruits.sort()
print( 'After Sorting' );
print( fruits );

max(), min() and sum() methods can also be used with lists in Python programming.

Example:

sampleNumbers = list();
sampleNumbers.append( 3 );
sampleNumbers.append( 1 );
sampleNumbers.append( 2 );
print ( 
    'Maximum is',
    max( sampleNumbers ) 
);
print ( 
    'Minimum is',
    min( sampleNumbers ) 
);
print ( 
    'Sum is',
    sum( sampleNumbers ) 
);

split() can be used to split the text by the delimiter to a list. If the delimiter is not mentioned, it makes use of blank space as the delimiter.

Example without delimiter:

strContent = input(
    'Please enter a statement: '
);
listContents = strContent.split();
for sampleContent in listContents :
    print( sampleContent );

Example with delimiter:

strContent = input(
    'Please enter text with : as delimiter'
);
listContents = strContent.split( ':' );
for sampleContent in listContents :
    print( sampleContent );

Leave a Reply