Python

Solved- TypeError: Dict_Values Object does not Support Indexing

Python’s implementation of an associative array data structure is dictionaries. A dictionary is a collection of key-value pairs. Each key pair is represented by a key pair and its associated value.

A dictionary is defined by a list of key-value pairs enclosed in curly braces and separated by commas. Each key’s value is separated by a comma in column ‘:’.

A dictionary cannot be sorted solely for the purpose of obtaining a representation of the sorted dictionary. Dictionaries are orderless by definition, but other types, such as lists and tuples, are not. As a result, you require an ordered data type, which is a list—most likely a list of tuples.

Solution for Dict_values object does not support indexing

We can solve this type error by using lists.

Error: ‘dict_values’ object does not support indexing

The dict.values() function returns a view object, and view objects cannot be indexed. If we try to select elements from it using indexing, we will receive the following error.

TypeError: ‘dict_values’ object does not support indexing

Take a dictionary and fetch all the values of the dictionary and print the first index then we get this error.

Implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# extracting the values
dictvalue = dictionary.values()
# printing the dictionary values
print(dictvalue)
print('now extracting the first index of dictvalue')
# printing the first index of dictvalue
print(dictvalue[0])

Output:

dict_values([200, 100, 300])
now extracting the first index of dictvalue
Traceback (most recent call last):
File "./prog.py", line 9, in <module>
TypeError: 'dict_values' object does not support indexing

Solution for this type error

To avoid this error, we can convert the view object dict values to a list and then index it. For example, we can convert the dict values object to a list object and then select an element from it at any index.

We can convert dictionary values to list easily by using list(given_dictionary_name. values())

In this case, we convert all of the values from the dictionary to a list and then chose the first element from the list, which is the first value from the dictionary’s first key-value pair.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# extracting the values and converting to list
dictvalue = list(dictionary.values())
# printing the dictionary values
print(dictvalue)
print('now extracting the first index of dictvalue')
# printing the first index of dictvalue
print(dictvalue[0])

Output:

[200, 100, 300]
now extracting the first index of dictvalue
200

Related Programs:

Solved- TypeError: Dict_Values Object does not Support Indexing Read More »

Python : How to Add an Element in List ? | append() vs extend()

A collection is an ordered list of values. There could be various types of values. A list is a mutable container. This means that existing ones can be added to, deleted from, or changed.

The Python list represents the mathematical concept of a finite sequence. List values are referred to as list items or list elements. The same value may appear multiple times in a list. Each event is regarded as a distinct element.

Given a list, the task is to add the elements to the givenlist using append and extend methods

Adding element to the list

We can add elements to list by several methods some of them are:

Method #1:Using append()

To add elements to the List, use the built-in append() function. The append() method can only add one element to a list at a time; loops are used to add multiple elements to a list using the append() method. Tuples can be added to the List using the append method because they are immutable. Lists, unlike Sets, can be appended to another list using the append() method.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BtechGeeks']
# adding element to the givenlist using append() function
givenlist.append('Python')
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BtechGeeks', 'Python']

Method #2:Using append() function to add multiple elements

Because a list can contain various types of elements, we can pass another list object as a parameter in append ()

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BtechGeeks']
# given elementslist which should be added
elementslist = ['python', 'code']
# adding elementslist to the givenlist using append() function
givenlist.append(elementslist)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BtechGeeks', ['python', 'code']]

Method #3:Using extend() function

Other than the append() and insert() methods for adding elements, there is extend(), which is used at the end of the list to add multiple elements at once.

Append() and extend() can only add elements at the end of a list.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BtechGeeks']
# given elementslist which should be added
elementslist = ['python', 'code']
# adding elementslist to the givenlist using append() function
givenlist.extend(elementslist)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BtechGeeks', 'python', 'code']

append() vs extend()

list.append(item) treats the parameter item as an individual object and appends it to the end of the list. Even if the given item is already in another list, it will be added to the end of the list as an individual object.

list.extend(item) treats parameter item as a new list and adds all of the list’s individual elements to the current list.
Related Programs:

Python : How to Add an Element in List ? | append() vs extend() Read More »

Check the First or Last Character of a String in Python

In Python, strings are sequences of bytes that represent Unicode characters. Due to the lack of a character data form in Python, a single character is simply a one-length string. To access the string’s components, use square brackets.

Examples:

Checking the last character:

Input:

string="BTechGeeks" lastcharacter='s'

Output:

Last character of string endswith s

Input:

string="BTechGeeks" lastcharacter='p'

Output:

Last character of string do no not end with p

Checking the first character:

Input:

string = 'BTechGeeks'  firstchar = 'B'

Output:

First character of string start with B

Input:

string = 'BTechGeeks'  firstchar = 'r'

Output:

First character of string do no not start with r

Checking the Last and First Character of the String

There are several ways to check first and last character of the string some of them are:

Checking last Character:

Method #1: Using negative slicing

Select the last element with a negative index to verify the condition on the string’s last character.

Below is the implementation:

# given string
string = 'BTechGeeks'
lastchar = 'p'
# check the last character ends with s
if(string[-1] == lastchar):
    print('Last character of string endswith', lastchar)
else:
    print('Last character of string do no not end with', lastchar)

Output:

Last character of string endswith s

Method #2:Using length of string

To check the condition on a string’s last character, first determine the length of the string. Then, at index size -1, check the content of the character.

Below is the implementation:

string = 'BTechGeeks'
lastchar = 's'
# calculating length of string
length = len(string)
# check the last character ends with s
if(string[length-1] == lastchar):
    print('Last character of string endswith', lastchar)
else:
    print('Last character of string do no not end with', lastchar)

Output:

Last character of string endswith s

Method #3:Using endswith()

If a string ends with the specified suffix, the endswith() method returns True; otherwise, it returns False.

Below is the implementation:

string = 'BTechGeeks'
lastchar = 's'
# calculating length of string
length = len(string)
# check the last character ends with s using endswith()
if(string.endswith(lastchar)):
    print('Last character of string endswith', lastchar)
else:
    print('Last character of string do no not end with', lastchar)

Output:

Last character of string endswith s

Method #4: Checking whether the string’s last character matches any of the given multiple characters

In comparison to the previous solutions, endswith() adds a new function. We may also move a tuple of characters to endswith(), which will check whether the last character of the string matches any of the characters in the specified tuple or not.

Below is the implementation:

# Given string and characters
string = 'BTechGeeks'
lastchars = ('s', 'p', 'e')
# check the first character of the given string
if(string.endswith(lastchars)):
    print('Given string ends with one of the given characters')

Output:

Given string ends with one of the given characters

Checking First Character:

Method #5:Using index 0 to get first character

A string is a set of characters, with indexing starting at 0. To find the first character in a string, select the character at the 0th index.

Below is the implementation:

# Given string and character
string = 'BTechGeeks'
firstchar = 'B'
# check the first character of the given string
if(string[0] == firstchar):
    print('First character of string start with', firstchar)
else:
    print('First character of string do no not start with', firstchar)

Output:

First character of string start with B

Method #6:Using startswith()

Python’s String class has a function called startswith() that takes a character or a tuple of characters and checks whether a string begins with that character or not. Let’s use this to see if our string’s first character is ‘B’

Below is the implementation:

# Given string
string = 'BTechGeeks'
firstchar = 'B'
# check the first character of the given string
if(string.startswith(firstchar)):
    print('First character of string start with', firstchar)
else:
    print('First character of string do no not start with', firstchar)

Output:

First character of string start with B

Method #7:Checking whether the string’s last character matches any of the given multiple characters

startswith () adds a extra function . We may also transfer a character tuple, and it will check if the first character of the string matches any of the characters in the tuple.

Below is the implementation:

# Given string and first char
string = 'BTechGeeks'
firstchars = ('s', 'p', 'B')
# check the first character of the given string
if(string.startswith(firstchars)):
    print('given string starts with one of the given characters')

Output:

given string starts with one of the given characters

Related Programs:

Check the First or Last Character of a String in Python Read More »

Python Pandas : How to convert lists to a dataframe

How to convert lists to a dataframe in python ?

As we know in python, lists are used to store multiple values in an ordered sequence inside a single variable.  Each element inside the list is called an item.

Syntax : my_list = [ element1, element2, element3, .....]

where,

  • elements/items are placed inside square brackets [].
  • items are separated by , symbol.
  • It can contain any number of items.
  • elements can be of different types i.e string, float, integer etc.

The pandas library is one of the most preferred tool to do data manipulation and analysis.

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Creating DataFrame from list of lists :

Now, let’s take an example.

#program :

import pandas as pd
#List of list
Data=[[‘apple’, ‘banana’, ‘orange’],[‘dog’, ‘cat’, ‘cow’],[‘potato’, ‘tomato’, ‘onion’]]
#creating a dataframe object from list of list
df=pd.DataFrame(Data)
Output:
       0          1               2
0  apple    banana    orange
1  dog        cat           cow
2  potato  tomato    onion

Creating DataFrame from list of tuples :

Now, let’s take an example.

#Program

import pandas as pd
#List of tuples
Data=[(‘apple’, ‘banana’, ‘orange’),(‘dog’, ‘cat’, ‘cow’),(‘potato’, ‘tomato’, ‘onion’)]
#creating a dataframe object from list of tuples
df=pd.DataFrame(Data)
Output:
       0             1                2
0  apple      banana     orange
1  dog          cat           cow
2  potato   tomato     onion

Converting list of tuples to dataframe and set column names and indexes :

We can also make the column and index names.

#Program 


import pandas as pd
#List of tuples 
Data=[(‘apple’, ‘banana’, ‘orange’),(‘dog’, ‘cat’, ‘cow’),(‘potato’, ‘tomato’, ‘onion’)] 
#Converting list of tuples to dataframe and set column names and indexes 
df=pd.DataFrame(Data, columns=[‘a’, ‘b’, ‘c’], index=[‘fruits’, ‘animals’, ‘vegetables’])
Output:
                       0              1                2
fruits             apple     banana      orange
animals          dog        cat           cow
vegetables    potato   tomato     onion

We can also skip one more than one columns like we have 3 rows and 3 columns

This can be used when you don’t need a column

so let’s try removing 1 column.

#Program 

import pandas as pd
#List of tuples 
Data=[(‘apple’, ‘banana’, ‘orange’),(‘dog’, ‘cat’, ‘cow’),(‘potato’, ‘tomato’, ‘onion’)] 
#Converting list of tuples to dataframe and set column names and indexes 
df=pd.DataFrame(Data, exclude=[‘2’], columns=[‘a’, ‘b’, ‘c’], index=[‘fruits’, ‘animals’, ‘vegetables’])
Output:
                       0              1
fruits           apple       banana
animals        dog           cat
vegetables  potato      tomato

Creating a dataframe from multiple lists :

We can also create a dataframe by giving multiple multiple lists.

Let’s try this:

#Program :

import pandas as pd
roll_no = [1, 2, 3]
name = [‘Tia’, ‘Raj’, ‘Rahul’]
state = [‘Goa’, ’Assam’, ‘Punjab’]
wrapoflist = list(zip(roll_no, name, state))
df = pd.DataFrame(wrapoflist, column=[‘roll_no’, ‘name’, ‘state’], index=[‘a’, ‘b’, ‘c’])
Output:
       roll_no  name        state
a        1         Tia           Goa
b        2         Raj          Assam
c        3        Rahul       Punjab

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Python Pandas : How to convert lists to a dataframe Read More »

Python : How to convert datetime object to string using datetime.strftime()

How to convert datetime object to string using datetime.strftime() function in python ?

In this article we’ll discuss how to convert datetime object to string using datetime.strtime() function.

Strptime() :

In Python, the time method strptime() generally parses a string which represents a time according to a format. The return value is a struct_time as returned by localtime().

Python strtime() is a class method in datetime class.

Let’s try with different examples:

#Program :

From datetime import datetime

#current date and time
now = datetime.now()
date_time = now.strftime(‘%m/%d/%Y , %H:%M:%S’)
print(‘date and time’, date_time)
Output :
date and time 04/24/2021 , 06:40:15

Here, ‘date_time’  is the string  and ‘now’ is a ‘datetime’ object.

Local’s appropriate date and time :

#Program

from datetime import datetime

timestamp = 1528797322
date_time = datetime.fromtimestamp(timestamp)

#Converting Date part to String
d = date_time.strftime(‘%c’)
print(‘1st output’, d)

#Converting Date part to String
d = date_time.strftime(‘%x’)
print(‘2nd output’, d)

#Converting datetime to text
d = date_time.strftime(‘%X’)
print(‘3rd output’, d)
Output :
date and time 04/24/2021 , 06:40:15
1st output: Sat Jan 12 09:55:22 2018
2nd output: 01/12/18
3rd output: 09:55:22

Here, format codes %c, %x, and  %X are used for local’s appropriate date and time representation.

Python : How to convert datetime object to string using datetime.strftime() Read More »

Python : How to Sort a list of strings ? | list.sort()

How to sort a list of strings using list.sort() in python ?

In this article we will discuss about 4 different ways of sorting a list of strings.

In python, list is a versatile data type which stores multiple elements in a single variable without caring about the types of data.

Syntax : my_list = [element1, element2, element3]

The 4 ways are

  1. By Alphabetical Order
  2. By Reverse Alphabetical Order
  3. By String Length
  4. By Numeric Order

List provides a sort() method by using which we can sort the elements of list from lower order to higher order.

So, let’s start exploring the topic.

Method-1 : By Alphabetical Order

Let’s see a program how it sorts in alphabetical order.

#Program :

#List Of Strings
my_list = ['bat' , 'ant', 'cat', 'eye', 'dog']
my_list.sort()
print(my_list)
Output :
['ant' , 'bat', 'cat', 'dog', 'eye']

Method-2 : By Reverse Alphabetical Order

Let’s see a program how it sorts in alphabetical order.

#Program :

#List Of Strings
my_list = ['bat' , 'ant', 'cat', 'eye', 'dog']
my_list.sort(reverse=True)
print(my_list)
Output :
['eye' , 'do', 'cat', 'bat', 'ant']

Here, sort() method accepts another argument reverse, and it it is True then it sorts the element. Default value is False. When set True, it sorts element in reverse order.

Method-3 : By String Length

Let’s see a program how it sorts in alphabetical order.

#Program :

#List Of Strings
my_list = ['apple' , 'ant', 'aeroplane', 'auto', 'a']
my_list.sort(key=len)
print(my_list)
Output :
['a' , 'ant',  'auto', 'apple', 'aeroplane']

Here, sort() method accepts another argument i.e key. During sorting each element of list will be compared with each other.

Syntax : list.sort(key=function)

Here we have passed len() function as key function. And all the element are sorted as per string length.

Method-4 : By Numeric Order

Suppose we have a list of strings, where each element are of numbers. There we can use int() as key function.

Let’s see a program how it sorts in alphabetical order.

#Program : 

#List Of Strings 
my_list = ['4' , '6', '1', '3', '2'] 
my_list.sort(key=int) 
print(my_list)
Output :
['1','2','3','4','6']

Python : How to Sort a list of strings ? | list.sort() Read More »

How to create DataFrame from Dictionary

Python Pandas : How to create DataFrame from dictionary ?

How to create DataFrame from dictionary in Python ?

In this article we will discuss about various ways of creating DataFrame object from dictionaries.

So, let’s start exploring different approaches to achieve this result.

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Method-1 : Create DataFrame from Dictionary using default Constructor :

In python DataFrame constructor accepts n-D array, dictionaries etc.

Syntax : pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
data = {
    'Name' : ['Satya', 'Omm', 'Rakesh'],
    'Age' : [21, 21, 23],
    'From' : ['BBSR', 'RKL', 'KDP']
}
  
# creating a Dataframe object 
df_obj = pd.DataFrame(data)
  
df_obj


Output :

         Name    Age   From
0      Satya      21      BBSR
1      Omm      21      RKL
2      Rakesh    23       KDP

All keys in dictionary are converted to column name and values in dictionaries converted column data.

Method-2 : Create DataFrame from Dictionary with custom indexes :

#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
data = {
    'Name' : ['Satya', 'Omm', 'Rakesh'],
    'Age' : [21, 21, 23],
    'From' : ['BBSR', 'RKL', 'KDP']
}
  
# creating a Dataframe object 
df_obj = pd.DataFrame(data, index = ['a','b','c'])
  
df_obj

Output :
        Name    Age     From
a      Satya      21      BBSR
b     Omm       21     RKL
c     Rakesh     23     KDP

By passing index list, we can avoid the default index.

Method-3 : Create DataFrame from Dictionary and skip data

By skipping some of the items of dictionary, we can also create a DataFrame object from dictionary

Let’s see the implementation of that.

#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
data = {
    'Name' : ['Satya', 'Omm', 'Rakesh'],
    'Age' : [21, 21, 23],
    'From' : ['BBSR', 'RKL', 'KDP']
}
  
# creating a Dataframe object 
#items skipped with key 'Age'
df_obj = pd.DataFrame(data, columns=['name', 'From'])
  
df_obj


Output :
       Name        From
0      Satya        BBSR
1     Omm          RKL
2     Rakesh       KDP

Method-4 : Create DataFrame from Dictionary with different Orientation

DataFrame can also be created from dictionary using DataFrame.from_dict() function.

DataFrame.from_dict(data, orient='columns', dtype=None)

It accepts orientation too, where we can pass the orientation as index then the keys which were used as columns during creating DataFrame now they will be used as index.

Let’s see the implementation of that.

#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
data = {
    'Name' : ['Satya', 'Omm', 'Rakesh'],
    'Age' : [21, 21, 23],
    'From' : ['BBSR', 'RKL', 'KDP']
}
  
# creating a Dataframe object 
#items skipped with key 'Age'
df_obj = pd.DataFrame(data,orient='index')
  
df_obj


Output :

             0           1            2

Aame   Satya   Omm     Rakesh

From     BBSR    RKL       KDP

Age       21         21         23

Method-5 : Create DataFrame from nested Dictionary :

Suppose we have a nested dictionary, then we ill directly pass it in DataFrame constructor where the keys of dictionary will be used as column.

Let’s see the implementation of that.

#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
# Nested Dictionary
data = { 
0 : {
    'Name' : 'Satya',
    'Age' : 21,
    'From' : 'BBSR'
    },
1 : {
    'Name' : 'Omm',
    'Age' : 21,
    'From' : 'RKL'
    },
2 : {
    'Name' : 'Rakesh',
    'Age' : 23,
    'From' : 'KDP'
    }
}
  
# creating a Dataframe object 
#items skipped with key 'Age'
df_obj = pd.DataFrame(data)
  
df_obj

Output :
             0           1            2
Aame   Satya   Omm     Rakesh
From     BBSR    RKL       KDP
Age       21         21         23

Read more Articles on Python Data Analysis Using Padas – Creating Dataframe Objects:

Python Pandas : How to create DataFrame from dictionary ? Read More »

Python: How to add or append values to a set ?

How to add or append values to a set in Python ?

In python add() method or append() method is used to simply add an item in set, tuple, dictionary etc.. but this method doesn’t add an element  if the entered element already present before it.

Adding a single element to the set :

Set is a data type which stores multiple items in a single variable and the items can be of different types.

Syntax : set.add(element)

It accepts an element as an argument and if that element is not present then it add it o the set.

Add a value to the set using add() function :

#program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"} 
# Adding a single element in set 
my_set.add(5) 
print(my_set)
Output :
{1,2,3,5'Hello','Hi'}

Adding a duplicate element to the set :

As set contains only unique elements, so duplicate elements so it will not not add the element again means set has no effect.

Let’s see an example program for it.

#program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"} 
# Adding 'Hello' in set 
my_set.add("Hello") 
print(my_set)
Output :
{1,2,3,5'Hello','Hi'}

Adding immutable objects to the set using add() function :

Set contains immutable elements. So, int, strings, bytes, frozen sets, tuples can be added as these are immutable object. But we can not add a list as it is mutable object.

Let’s see an example program for it how we can add a tuple to the set using add function.

#Program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"}
# Adding a tuple in set
my_set.add((4, 5))
print(my_set)
Output :
{1, 2, (4,5),"Hello", 3, "Hi"}

Adding a mutable object to set will give TypeError :

Suppose we are trying to add a list as it is mutable object. It will give Type error.

Let’s see an example program for it.

#Program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"}
# Adding a tuple in set
my_set.add([21, 31])
print(my_set)
Output :
TypeError: unhashable type: 'list'

Adding multiple elements to the set :

By using update() method we can add elements to the set.

Syntax : set.update(*args)
#Program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"}
# Adding 10,20,30 in set
#update() method is used
my_set.update((10, 20, 30))
print(my_set)
Output :
{1,2,3,5'Hello','Hi',10,20,30}

Adding elements from multiple sequences to the set :

Suppose we want to add a list, tuple at a time. Then let’s see how it works.

#Program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"}

#list initialized
my_list= [10, 20, 3]
#tuple initialized
my_tuple = (31, 32)
#update() method is used
my_set.update(my_list,my_tuple)
print(my_set)
Output :
{1,2,3,5'Hello','Hi',10,20,30,31,32}

Adding dictionary keys to the set :

#Program :

#Set initialized
my_set = set()
#dictionary initialized
my_dict = {'Satya': 11, 'Omm': 12, 'Nitya': 15}
#only keys ill be added
my_set.update(my_dict)
print(my_set)
Output :
{'Satya','Omm','Nitya'}

When we will pass the dictionary inside the update() method then only key will be added in the set.

Adding dictionary values to the set :

#Program :

#Set initialized
my_set = set()
#dictionary initialized
my_dict = {'Satya': 10, 'Omm': 20, 'Nitya': 30}
#only keys ill be added
my_set.update(my_dict.values())
print(my_set)
Output :
{10,20,30}

When we will pass the dictionary_name.values() inside the update() method then only values will be added in the set.

 

Python: How to add or append values to a set ? Read More »

Python : Get number of elements in a list, list of lists or nested list

How to get the number of elements in a list, list of lists or nested list in Python ?

In this article we will discuss about different ways to get number of elements in a list, lists of lists or nested list Lists. As we know in python, lists are used to store multiple values in an ordered sequence inside a single variable.  Each element inside the list is called an item.

Syntax : my_list = [ element1, element2, element3, .....]

where,

  • elements/items are placed inside square brackets [].
  • items are separated by , symbol.
  • It can contain any number of items.
  • elements can be of different types i.e string, float, integer etc.

Count elements in a flat list :

To count elements in a flat list we have to use the len( ) function. This len( ) function is a built-in function that returns the number of items inside a list, tuple, or string.

Syntax : len(name_of_list)

Let’s see an implementation of it.

#Program :

#list of items
listElem = ['contempt', 'speech', 'notorious', 'north','south','aware','ex']
#finding the length of list
length = len(listElem)
print('Number of elements inside the list : ', length)
Output : 
Number of elements in list :  7

Count elements in list of lists :

To count the number of elements inside a list of lists we can not use the len( ) function because as the function works it will return the number of lists inside the list.

Let’s see an implementation of it.

#Program :

#list of items
listElem = [[10,20,30],[40,50,60],[70,80,90]]
#finding the length of list of lists
length = len(listElem)
print('Number of elements inside the list : ', length)
Output : 
Number of elements in list :  3

As you can see there are 9 elements inside the list, however, the function returned 3, which is the number of lists inside the list.

So to count elements we can use two methods.

Method-1 : Using for loop to iterate over the list and count the elements :

#Program : 

#list of lists 
listElem2D = [[10,20,30],[40,50,60],[70,80,90]] 
count = 0 
#counting number of elements 
for listElem in listElem2D: 
 count += len(listElem) 
print('Total Number of elements : ', count)
Output :
Total Number of elements :  9

Method-2 : Using list comprehension :

Using list comprehension to iterate over the list, build a new list of sizes and calculate the number of elements by passing it to the built-in sum( ) function.

#Program :

#list of lists
listElem2D = [[10,20,30],[40,50,60],[70,80,90]]
#finding number of elements
count = sum( [ len(listElem) for listElem in listElem2D])                 
print('Total Number of elements : ', count)
Output : 
Total Number of elements :  9

Use list.__len__() to count elements in a list :

We can call the __len__() member function of list to get the size the list.

#Program : 

#list of items 
listElem = [10,20,30,40,50] 
#finding the length of list of lists 
length = listElem.__len__()
print('Number of elements inside the list : ', length)
Output :
Number of elements inside the list : 5

Count elements in a nested list :

Nested lists might contain several lists, lists of lists, or values together so we can not use any of the above approaches for it. So to calculate the values we have to write a function that takes the nested list and returns the number of items inside it.

Let’s see an implementation of it.

#Program :

def getSizeOfNestedList(listOfElem):
    count = 0
    for elem in listOfElem:
        if type(elem) == list:
            count += getSizeOfNestedList(elem)
        else:
            count += 1    
    return count

#list of lists
listElemNested = [[10,20,30],[40,50,60],[70,80,90],100,120,140,[[110,130],150],170]
count = getSizeOfNestedList(listElemNested)                
print('Total Number of elements : ', count)
Output :
Total Number of elements :  16

 

Python : Get number of elements in a list, list of lists or nested list Read More »

Python Programming – Package

In this Page, We are Providing Python Programming – Package. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Package

Package

As discussed previously, functions and global variables usually reside inside a module. There might be a scenario where organizing modules needs to be done. That is where packages come into the picture. Packages are just folders of modules with a special ” ____init___ .py” file, that intimate Python that this folder is special because it contains Python modules. In the simplest case, ” ____init_____ .py” can just be an empty file, but it can also execute initialization code for the package or set _____all _____variables, described later.

Suppose there is an objective to design a collection of modules (a “package”) for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: .wav, .aiff, .au), so it might be needed to create and maintain a growing collection of modules for the conversion between the various files formats. There are also many different operations that are needed to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so there will be numerous modules to perform these operations. Here is a schematic structure for the package:

sound/                                                            Top-level package
                      _____init_____ .                           py Initialize the sound package
formats/                                                          Subpackage for file format conversions
                    _____init______ .py
                    wavread . py 
                    wavwrite . py 
                    aiffread . py 
                    aiffwrite . py 
                    auread . py 
                    auwrite . py
                    . . . 
effects/                                                            Subpackage for sound effects
                     _____init_______ .py
                     echo . py 
                     surround . py
                     reverse . py
                      . . . 
filters/                                                               Subpackage for filters
                     _____init_______ .py
                     equalizer . py 
                     vocoder . py 
                     karaoke . py
                     . . .

When importing the package, Python searches through the directories on sys .path looking for the package subdirectory. Users of the package can import individual modules from the package, for example:

import sound . effects . echo

This loads the sub-module sound. effects. echo. It must be referenced with its full name.

sound . effects . echo . echofilter ( input , output , delay=0 . 7 , atten=4 )

An alternative way of importing the sub-module is:

from sound .  effect's import echo

This loads the sub-module echo, and makes it available without its package prefix, so it can be used as follows:

echo . echofilter ( input , output , delay=0 . 7 , atten=4 )

Yet another variation is to import the desired function or variable directly:

from sound . effects . echo import echofilter

This makes echofilter ( ) directly available:

echofilter ( input , output , delay=0 . 7 , atten=4 )

Note that when using from package import item, the item can be either a sub-module (or sub-package) of the package, or some other name defined in the package, like a function, class, or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised. Contrarily, when using syntax like import item, subitem, sub subitem, each item except for the last must be a package; the last item can be a module or a package but cannot be a class or function or variable defined in the previous item.

Importing * from a package

What happens when the programmer writes from sound, effects import *? Ideally, one would hope that this somehow goes out to the file system, finds which sub-modules are present in the package, and imports them all. This could take a long time.

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s _____init_____ .py code defines a list named _____all_____, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they does not see a use for importing * from their package. For example, the file sounds/effects/ ____init_____ .py could contain the following code:

____all_____ = [ " echo " ,  " surround " ,  " reverse " ]

This would mean that from the sound. effects import * would import the three named sub-modules of the sound package.

If _____all_____ is not defined, the statement from sound, effects import * does not import all sub-modules from the package sound. effects into the current namespace; it only ensures that the package sound. effects have been imported (possibly running any initialization code init .py) and then imports whatever names are defined in the package. This includes any names defined (and sub-modules explicitly loaded) by ____init______ .py. It also includes any sub- .rhodules of the package that were explicitly loaded by previous import statements.

Remember, there is nothing wrong with using from Package import specific___submodule. In fact, this is the recommended notation, unless the importing module need to use sub-modules with the same name from different packages.

Intra-package references

The sub-modules often need to refer to each other. For example, the surround module might use the echo module. In fact, such references are so common that the import statement first looks in the containing package before looking in the standard module search path. Thus, the surround module can simply use import echo or from echo import echofilter. If the imported module is not found in the current package (the package of which the current module is a sub-module), the import statement looks for a top-level module with the given name.

When packages are structured into sub-packages (as with the sound package in the example), the programmer can use absolute imports to refer to sub-modules of siblings packages. For example, if the module sound, filters .vocoder needs to use the echo module in the sound. effects package,it can use from sound.effects import echo.

Starting with Python 2.5, in addition to the implicit relative imports described above, the programmer can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use:

from . import echo
from . . import formats
from . .filters import equalizer

Packages in multiple directories

Package support one more special attribute, ____path____ . This is initialized to be a list containing the name of the directory holding the package’s ___init____ .py before the code in that file is executed. This variable can be modified, doing so affects future searches for modules and sub-packages contained in the package. While this feature is not often needed, it can be used to extend the set of modules found in a package.

>>> import numpy 
>>> numpy. _____path_____
[ ’ C : \ \ Python27 \ \ lib \ \ site - packages \ \ numpy ' ]

Python Programming – Package Read More »