-4

For example there is a list called Demo_list.

Demo_list = [4,5,6,7]

If i give

Demo_list[0]

we will get value as 4.

But if i gave only Demo_list[0] i want to get square of that value and the list should not be modified.

Is it possible?

4 Answers4

0

Yes, it is possible.

variable = Demo_list[0]**2

The code above won't modify the list.

kiyah
  • 1,502
  • 2
  • 18
  • 27
  • I already said that i have to give only Demo_list[0] then i should get the square of that. i don't want to give any like ur following answers. I just want to give Demo_list[0], i.e; i want to override internal functions – Praveen JP Jan 31 '18 at 09:34
0
demo_list = [4, 6, 7, 8]
for i in range (len(demo_list)):
    j = demo_list[i] * demo_list[i]
    print j

May be you are looking something like that..

Sachhya
  • 1,260
  • 1
  • 9
  • 16
  • I already said that i have to give only Demo_list[0] then i should get the square of that. i don't want to give any like ur following answers. I just want to give Demo_list[0], i.e; i want to override internal functions – Praveen JP Jan 31 '18 at 09:34
  • means you want to use index value as a square but index should not be modified.. i don't think it is a good idea because when you going to access its value without manipulation it only shows what value it hold. – Sachhya Jan 31 '18 at 09:48
  • Ok thanks but i know that, so only i asked about overriding internal function. – Praveen JP Jan 31 '18 at 09:51
0

You can use the < math > function

import math
print ( math.pow(demo[0],2)

where, 2 is the power that you want to raise the value in demo[0].

Edit (Inheriting from the collections, and overriding the abstract list methods , in your case (getitem),that you wish to modify).

import collections class MyList(collections.MutableSequence): def __init__(self, *args): self.list=list() self.extend(list(args)) def __len__(self): return len(self.list) def __getitem__(self,i): return (self.list[i]**2) def __delitem__(self,i): del self.list[i] def __setitem__(self,i,v): self.list[i]=v def insert(self,i,v): self.list.insert(i,v) def __str__(self): return str(self.list)

Note: When you override these abstract methods, you need to define your list, with the type, you declared in this class. i.e.,

demo_list=MyList(1,2,3,4) demo_list[1]

Output : 4

Sandvip
  • 11
  • 4
  • I already said that i have to give only Demo_list[0] then i should get the square of that. i don't want to give any like ur following answers. I just want to give Demo_list[0], i.e; i want to override internal functions – Praveen JP Jan 31 '18 at 09:33
  • Please refer to the _Edit_ section in the answer above. – Sandvip Feb 01 '18 at 06:35
0
#For complete list
SqrtList = [x**2 for x in Demo_list]
#For single element
Sqrtvariable = Demo_list**2
Arun
  • 31
  • 3