Python: I do not understand the complete usage of sum() - python

Of course I get it you use sum() with several numbers, then it sums it all up, but I was viewing the documentation on it and I found this:
sum(iterable[, start])
What is that second argument "[, start]" for? This is so embarrasing, but I cannot seem to find any examples with google and the documentation is fairly cryptic for someone who tries to learn the language.
Is it a list of some sort? I cannot get it to work. Here is an example of one of my attempts:
>>> sum(13,4,5,6,[2,4,6])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum expected at most 2 arguments, got 5

The start indicates the starting value for the sum, you can equate this:
sum(iterable, start)
with this:
start + sum(iterable)
The reason for your error is that you're not encapsulating the numbers to sum in an iterable, do this instead:
sum([13, 4, 5, 6])
This will produce the value of 28 (13+4+5+6). If you do this:
sum([13, 4, 5, 6], 25)
You get 53 instead (13+4+5+6 + 25).

Also, please keep in mind that if you create a nested list (like you sortof have above) sum will give you an error (trying to add an integer to a list, isn't clear - are you trying to append or add it to the sum of the list or what?). So will trying to use two lists, + is overloaded and would just normally concatenate the two lists into one but sum tries to add things so it wouldn't be clear what you're asking.
It's easier to explain with examples:
>>> mylist = [13, 4, 5, 6, [2,4,6]]
>>> sum(mylist)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> a = [13, 4, 5, 6]
>>> b = [2,4,6]
>>> c = [a,b]
>>> c
[[13, 4, 5, 6], [2, 4, 6]]
>>> sum(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> c = a+b
>>> c
[13, 4, 5, 6, 2, 4, 6]
>>> sum(c)
40
>>> sum(c, 23)
63
Hope this helps.

Related

Why am I getting a type error for the second pice of code while the first on worked?

Code:
import numpy as np
#generate some fake data
x = np.random.random(10)*10
y = np.random.random(10)*10
print(x) #[4.98113477 3.14756425 2.44010373 0.22081256 9.09519374 1.29612129 3.65639393 7.72182208 1.05662368 2.33318726]
col = np.where(x<1,'k',np.where(y<5,'b','r'))
print(col) #['r' 'r' 'r' 'k' 'b' 'b' 'r' 'b' 'r' 'b']
t = []
for i in range(1,10):
t.append(i)
print(t) #[1, 2, 3, 4, 5, 6, 7, 8, 9]
cols = np.where(t % 2 == 0,'b','r')
print(cols)
Error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-58-350816096da9> in <module>
6 print(t)
7
----> 8 cols = np.where(t % 2 == 0,'b','r')
9 print(cols)
TypeError: unsupported operand type(s) for %: 'list' and 'int'
I am trying to generate color code, blue for even and red for odd numbers.
Why do I get the error here, while it worked in the first piece of code?
The "first time" in your code snippet, x and y are numpy arrays, created from the calls to np.random.random:
col = np.where(x<1,'k',np.where(y<5,'b','r'))
This is not the case with t. As some of the comments have indicated, t is a generic Python list. You cannot apply the mod operator to a Python list.
>>> [1, 2, 3, 4] % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'list' and 'int'
You can, however, apply the mod operator to a numpy array as Barmar indicated:
t = np.array([2,3,4,5])
t % 2
# returns array([0, 1, 0, 1])
np.where(t % 2 == 0, 'a', 'b')
# returns array(['a', 'b', 'a', 'b'], dtype='<U1')

Working with lists and slicing

This seems like an easy task and I honestly don't know what the problem is. I have a list such as [0,1,2,3,4,5,6] and such and I need to pick and index, lets say 3, and the output should look like [4,5,6,3,0,1,2] and here is my code
def cut_list(listA, index):
return listA[index+1:] + listA[index] + listA[0:index]
Yet the listA[index] function isn't working properly and giving an error, however if I take out the other parts and only do "return listA[index]" it will output 3
listA[index] is a scalar value which can't be concatenated with a list. You're doing something akin to:
>>> 3 + []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Lists can only be concatenated with other lists, so the solution is to simply change listA[index] into a list with that as the only element. e.g. [listA[index]]:
def cut_list(listA, index):
return listA[index+1:] + [listA[index]] + listA[0:index]
To make it work for most sequence types, we can do a little clever slicing:
def cut_list(listA, index):
return listA[index+1:] + listA[index:index+1] + listA[0:index]
This works because the slice x[idx:idx+1] should return a sequence of the same type as x that has only the idx'th element from x.
>>> cut_list(range(10), 3)
[4, 5, 6, 7, 8, 9, 3, 0, 1, 2]
>>> cut_list('foo3bar', 3)
'bar3foo'
>>> cut_list(tuple(range(10)), 3)
(4, 5, 6, 7, 8, 9, 3, 0, 1, 2)

TypeError: 'itertools.combinations' object is not subscriptable

When I try to run:
temp = (twoset2[x][i][0]-twoset[x][i][1])
I get:
TypeError: 'itertools.combinations' object is not subscriptable
My code:
for x in range(0,64):
for i in range(0,1):
temp = (twoset2[x][i][0]-twoset[x][i][1])
DSET[counter2]= temp
temp = 0
counter2 += 1
Basically what I am trying to do is: I have a list (twoset2) of 2 element subsets of coordinates (so an example: ((2,0) (3,3)). I want to access each individual coordinate, and then take the difference between x and y and place it into DSET, but I get the above error when trying to run.
Please help!
itertools.combinations returns a generator and not a list. What this means is that you can iterate over it but not access it element by element with an index as you are attempting to.
Instead you can get each combination like so:
import itertools
for combination in itertools.combinations([1,2,3], 2):
print combination
This gives:
(1, 2)
(1, 3)
(2, 3)
twoset2 is not a list; it is an itertools.combinations object (which does not support indexing):
>>> import itertools
>>> itertools.combinations([1, 2, 3], 2)
<itertools.combinations object at 0x01ACDC30>
>>>
>>> twoset2 = itertools.combinations([1, 2, 3], 2)
>>> twoset2[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'itertools.combinations' object is not subscriptable
>>>
You will need to explicitly convert this into a list if you want a list:
twoset2 = list(itertools.combinations(...))

How can you join int and list together?

But I still can't find the join function anywhere else on the internet. The main problem is that the head(items) is int and tail(items) is list, and I can't combine head and tail together. Here is the code I tried:
def head(items):
return items[0]
def tail(items):
return items[1:]
def isEven(x):
return x % 2 == 0
def extractEvens(items):
if (items == None):
return None
elif (isEven(head(items))):
return join(head(items),extractEvens(tail(items)))
else:
return extractEvens(tail(items))
a = [4,2,5,2,7,0,8,3,7]
print(extractEvens(a))
Here is the link for the page I tried to study: The is the code for filter pattern:
link_of_code
You can also try insert which is even more useful as the head must be in the starting.
l = extractEvens(tail(items))
l.insert(0,head(items))
return l
Please, provide an example of the desired output.
If you want to create a new list, merging a list with an int, it should be:
return [head(items)] + tail(items)
what you need is append
>>> a=6
>>> b=[1,2,3,4]
>>> b.append(a)
>>> b
[1, 2, 3, 4, 6]
here you just cant concanate list and int:
>>> a=6
>>> b=[1,2,3,4]
>>> a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> list(a)+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
but if you do str, it will concanated as str not int:
>>> list(str(a))+b
['6', 1, 2, 3, 4]
There are multiple errors in your code:
def isEven(x):
return x % 2 == 0 # x % 2 not x % ==
def extractEvens(items):
if not items:
return [] # return empty list not None
elif isEven(head(items)):
# convert ints to strings and put head(items) in a list
return "".join(map(str,[head(items)]) + map(str,extractEvens(tail(items))))
else:
return extractEvens(tail(items))
You can also do this in a single list comprehension:
a = [4, 2, 5, 2, 7, 0, 8, 3, 7]
print("".join([str(x) for x in a if not x % 2]))

Strange error with range type in list assignment

r = range(10)
for j in range(maxj):
# get ith number from r...
i = randint(1,m)
n = r[i]
# remove it from r...
r[i:i+1] = []
The traceback I am getting a strange error:
r[i:i+1] = []
TypeError: 'range' object does not support item assignment
Not sure why it is throwing this exception, did they change something in Python 3.2?
Good guess: they did change something. Range used to return a list, and now it returns an iterable range object, very much like the old xrange.
>>> range(10)
range(0, 10)
You can get an individual element but not assign to it, because it's not a list:
>>> range(10)[5]
5
>>> r = range(10)
>>> r[:3] = []
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
r[:3] = []
TypeError: 'range' object does not support item assignment
You can simply call list on the range object to get what you're used to:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> r = list(range(10))
>>> r[:3] = [2,3,4]
>>> r
[2, 3, 4, 3, 4, 5, 6, 7, 8, 9]
Try this for a fix (I'm not an expert on python 3.0 - just speculating at this point)
r = [i for i in range(maxj)]

Categories