Using arithmetic operators with a variable holding a list - python

I am quite confused on this, so I hope someone can help me.
So what I have is basically a list in Python, then I have set a variable which within I have used the list name and called the first element such as myVariable = myList[0], now basically what I want to do is to add an integer value to myVariable to make it so that I get the next value in the list myList[1] and subtract the list as a whole by one each time. I have 8 different elements/items in the list so far.
I keep getting an error usually something along the lines that I can't add an integer (the number value) to the myVariable as it sees it as a string, and I'm unsure on how to get the list to move one result forward and once that's done then subtract the list by one result as it is intended to be removed each time it loops.
Example:
def testFunction(testValue):
myVariable = myList[0]
testResult (myVariable + testValue) - 1
print testResult
The testValue being an integer, I need to get the value from myList depending on the integer value of testValue (which it's being added with), so if the testValue was like 3 it would add that to the default myVariable value which is currently 0, then after that result from the list and continue doing this until there is only one result left in this list, which currently consists of 8 elements.
UPDATE:
Sample list:
["KaPow", "Boom", "Pow", "Shapow", "Crash", "Whoosh", "Bang", "Pew"]
I enter a value into a function such as 3, function below:
bam(bamtypes, choice):
I enter the suggested value of 3 as "choice" and the bamtypes is just the given list above, then I should receive back the value Shapow. Then what I want to do is basically add myVariable to testValue (I referred to the integer of "choice" in the function when referring to testValue, so in this case it'll be 3). I also referred to bamtypes when saying myList.
As myVariable basically set to tell the function to begin from the first element in the list such as myVariable = bamtypes[0], but then I want the 3 value from "choices" to be added to the myVariable, so that it becomes bamtypes[3] then I can use .pop to extract that value, then does it again so it is bamtypes[6] and so on until the list only leaves one result. Also note as the list has 8 elements, what I want to do is once the 3 adds to the bamtypes[6] it should give me the value of [0] again as it resets, counting twice to the 8th element then returns once more to 0, using up the value 3 for that given retrieval.

When you are doing an arithmetic operation, you can either store the result in a variable or ignore the result. If we want to store in a variable, we need to use assignment operator, like this
testResult = (myVariable + testValue) - 1 # Note the `=` symbol
The error you get means that the data stored in myVariable is not a number but a character string. So, you should convert that to an integer like this
testResult = (int(myVariable) + testValue) - 1 # Note the `int` function

Related

TypeError: list.append() takes exactly one argument (2 given) error when appending array through iteration

i want my code to find the position of capital letters and add them to an array. After testing, i get the error: TypeError: list.append() takes exactly one argument (2 given)
also when testing with a input with a singular capital letter it works fine, however when they are multiple capital letters, the array will only contain the last position.
for i in range(0,length):
letter = camel_case[i]
for k in range(0,25):
check = capitals[k]
if check == letter:
position = i
print(f"{position}")
global caps
caps = []
caps.append(capital_quantity,i)
capital_quantity = capital_quantity + 1
else:
pass
The error is self-explanatory. The append function only takes a single parameter but two were passed.
Replace the following line of code:
caps.append(capital_quantity,i)
with this:
caps.append(capital_quantity)
For lists, you can only append one item at a time. If you would like to keep capital_quantity and i together you could append them to your list as a secondary list i.e.
caps.append([capital_quantity,i])
Its worth noting, if for whatever reason you want to add both values to your list in a flat structure rather than a nested list you could use the.extend() method. This is a good tutorial to understand the behavior.
Seems like you got list.append and list.insert mixed up.
list.append takes in one argument to add to the end of the list, whereas list.insert takes both a positional argument and the item to insert in that position of the list.
Additionally, there appears to be other bugs/fixes in your code.
range(0,25) should be range(0,26) since the last item in the range will be one less than the end argument (numbers 0-24 instead of 0-25)
caps=[] sets the list caps to an empty list every time it's called. I don't think that's what you want.
You don't need the else:pass
You don't need the capital_quantity. Just use list.append. If you need to count how many capitals are in the list, just do len(caps)
Here's how I'd implement this problem the most straightforward way:
caps=[]
for i,c in enumerate(camel_case):
if c.isupper():
caps.append(i)
We check if each character c in the string camel_case is uppercase, and if it is, we append its index i to the list.
You can save two or more data in a list with curly braces like this.
caps.append({capital_quantity,i})

Why my return statement is not showing any output?

I was trying to solve the following problem: Draw a star pattern that increases in every step (1st step: 1 star, 2nd step: 2 stars). E.g.
*
**
I am not sure why my code is not showing any output when I am writing return? When I am writing print, it is giving me the star output but also giving me None. May I know why return or print are not working properly? I am using Python 3.7. My code is:
def string(inp):
for i in range (inp):
return i*"*"
print (string(5))
range starts at 0, and return terminates a function, so that means string will always return an empty string.
Here's one possible option for getting your expected result:
def stars(n):
for i in range(1, n+1): # Add one to start and stop
print(i * "*") # Print inside the function
stars(2) # Don't print outside the function
Output:
*
**
If you need to print outside the function, you could use a generator:
def stars(n):
for i in range(1, n+1):
yield i * "*" # "yield" is like "return" but can be used more than once
for s in stars(2):
print(s) # Print each string that gets yielded
# Or print all at once, using the "splat" unpacking operator
print(*stars(5), sep='\n')
Using return won't print an output, use something like this:
def string(inp):
for i in range (inp):
print(i*"*")
string(5)
also this will only print 4, if you make it
for i in range(inp + 1):
It will work as intended,
hope this helps!
I will translate the code to plain English, as explicitly as I can:
Here are the rules that take a value `inp` and compute the `string` of that `inp`:
Letting `i` take on each integer value from 0 up to but not including `inp`:
We are done. The `string` of `inp` is equal to the string '*' repeated `i` times.
Compute the `string` of `5` and display it.
Hopefully the problem is evident: we can only be done with a task once, and i is equal to 0 at that point, so our computed value is an empty string.
When I am writing print, it is giving me the star output but also giving me None
From the described behaviour, I assume that you mean that you tried to replace the word return in your code with print, giving:
def string(inp):
for i in range (inp):
print(i*"*")
print (string(5))
That produces the triangle, of course, except that
Since i will be equal to 0 the first time through the loop, a blank line is printed; and since i will be equal to 4 the last time through the loop, there is no ***** line.
At the end, None is printed, as you describe. This happens because the value computed by string is the special value None, which is then printed because you asked for it to be printed (print(string(5))).
In Python, each call to a function will return a value when it returns, whether or not you use return and whether or not you specify a value to return. The default is this special None value, which is a unique object of its own type. It displays with the text None when printed, but is different from a string with that text (in the same way that the integer 5 is different from the string "5").
May I know why return or print are not working properly?
They are working exactly as designed. return specifies the result of calling the function, and can only happen once per function, and does not cause anything to be displayed. print displays what it is given.
If you wish to return multiple values from a call, then you need to work around that restriction - either by using a generator instead (as in #MadPhysicist's or #wjandrea's answers), or by using some single, structured datum that contains all those values (for example, a list, or a tuple).
A a re-entrant function that preserves state between calls is a generator. To make a generator function, change the keyword return to yield:
def string(n):
for i in range(n):
yield (i + 1) * '*'
Calling this version of string will return a generator that yields a new line of your desired output at each iteration.
To print:
for line in string(5):
print(line)
To print all at once:
print('\n'.join(string(5)))

How to use replace() function to change string items in global list?

I`ve tried to use replace function inside of while loop. My main aim is change specific index item with different string in a global list name is tryList in the code block.
when I checktryList[counter][3].replace(tryList[counter][3],newItem) output by using print() function;
I am able to see expected string value is given but at the end when I control global list, nothing is changed.
tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList)
counter=0
while counter<loop:
tryList[counter][3].replace(tryList[counter][3],newItem)
counter=counter+1
Could you please help me what am I doing wrong?
Strings are immutable, so you replace method does not alter the string itself, it creates a new, modified string. So, instead of
lst[3].replace.replace("a", "b)
write
lst[3] = lst[3].replace("a", "b)
Try this to change the 3rd element of each list to "ana":
tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList)
counter=0
while counter<loop:
tryList[counter][2] = tryList[counter][2].replace(tryList[counter][2],newItem)
counter=counter+1

when assigning to a variable list index out of range?

n = int(input())
numb = input()
lis = list(map(int, numb.split()))
lis.sort()
a = lis[n]
for i in (0,len(lis)):
if lis[i]=[a]
print (lis[i-1])
I tried this and when I enter input of 5 for n and the lis as 24689 it says there is an error in the line where a=lis[n] saying the list index is out of range.
The problem is probably with the line
for i in (0,len(lis)):
Lists are zero-based so the valid indexes are from 0 to len(lis) - 1. len(lis) is indeed out of range.
Also, notice that the above line of code means that i will receive only 2 values - 0 and len(lis). Is that what you really mean? If you meant to go over all the indexes, you will need to do
for i in range(len(lis)):
range(n) is an iterator that returns the values from 0 to n - 1.
There are several problems with this code. Firstly, you need to change your for statement to for i in range(0, len(lis)) because you're not currently calling the range function.
Also, on the first iteration, it will try to access index -1, which is the last element in the list. A better idea is to change your range function to range(0, len(lis) - 1), and changing the print statement on the last line to print(lis[i]) to fix the problem of receiving the last element by using the index -1.
P.S. Welcome to Stack Overflow!
Wow, Keep note that what you thought would happen on your third line wasn't the case and is 1 of the 2 problems of your error message. and that 1 problem was due to one single function you used which I have sequentially demonstration below;
I assume you were expecting each character of the string '24689' to be transformed to an integer by the map() function*, then converted to a list by the list() function*, then stored in the Variable ...lis... for later further usage. You were expecting something like [2,4,6,8,9] as Lis`.
Well you almost had that if not for your decision to use split() on Numb.
The Split function will run first and turn the '24689' into a
different iterable, in this case changing '24689' to a list ['24689'].
Then the map() will map every item in this iterable ['24689'] to an
integer. In this case only 1 item exist in the list which is '24689'.
So it maps that item as an integer.
Then the list() function stores this single item which is now an
integer in a list owned by the variable Lis. So you finally get
[24689]. And this is different from your [2,4,6,8,9] expectation.
As I've demonstrated above, so the cause of all this problem was your decision to use Split().
if you take away the split(), then;
the map() will no longer see just one Item but rather '2' '4' '6' '8'
'9' because a string '24689' is an iterable, with 5 individual items in
your case. So the map() runs over all these 5 items in your Numb string and
maps/transforms them to individual integers respectively. Then finally
the List() would have stored all these beautiful individual integers
in a list Owned by the variable Lis.And you get your desired [2,4,6,8,9] in return for the Variable Lis.
So the correct statement for that very line is:
lis = list(map(int, numb)) // This line should now produce [2,4,6,8,9]
The second problem of your error was the value you assigned to the index variable 'n' of list[n]. I assume you wanted to fetch the fifth item in the list. This 'n' is the linear count of items(in your case the individual numbers - 2,4,6,8,9). This counting start from 0 for the first letter instead of 1. Normally when you count items, the first letter is 1 but for index count in python list[n], the first letter is 0 instead of 1 so in your case the fifth item will be indexed as 4 since index count start from 0. So your 'n' input should be 4
These 2 solutions above solves your the specific error you mentioned.
BUT aside from your question above, your entire code will still run into another error even if the above solutions are implemented. This is Due to errors on these following lines as well:
On line 6:
for i in (0,len(lis)): //Wrong due to NO function name called before '(0, len(lis))'.
We will logically assume you want to use the range function
correct expression on LINE 6 is:
for i in range(0, len(lis)):
On Line 7:
if lis[i]=[a] //Three problems on this line...
First, you can't compare two objects with the operator '='. instead use '=='
Second, [a] is a meaningless value in your expression... Does comparing that to a number look right to you? I bet No. Remember [a] is not the same as the variable 'a'.
a = lis[n], while [a] = [lis[n]]
So the correct expression there should be 'a' and not '[a]'
Last, you need to add ':' after every "if", "for" or "while" expression..
Here is how LINE 7 should CORRECTLY look like,
if lis[i] == a:
All the above solutions should satisfy your need. So the complete correct code for your script should look like this:
n = int(input())
numb = input()
lis = list(map(int, numb))
lis.sort()
a = lis[n]
for i in range(0,len(lis)):
if lis[i] == a:
print (lis[i-1])

How to write a function with a list as parameters

Here is the question, I'm trying to define a function sample_mean that takes in a list of numbers as a parameter and returns the sample mean of the the numbers in that list. Here is what I have so far, but I'm not sure it is totally right.
def sample_mean(list):
""" (list) -> number
takes in a list of numbers as a parameter and returns the sample mean of the the numbers in that list
sample_mean =
sample_mean =
"""
mean = 0
values = [list]
for list in values:
print('The sample mean of', values, 'is', mean(list))
Firstly, don't use list as a name because it shadows/hides the builtin list class for the scope in which it is declared. Use a name that describes the values in the list, in this case samples might be a good name. The function could be implemented with something like this:
def sample_mean(samples):
total = 0
for value in samples:
total = total + value
return total / float(len(samples))
Or a shorter version which avoids writing your own loop by making use of Python's sum() function :
def sample_mean(samples):
return sum(samples) / float(len(samples))
Call the function like this:
>>> print(sample_mean([1,2,3,4,5]))
3.0
Note the use of float() to ensure that the division operation does not lose the fractional part. This is only an issue in Python 2 which uses integer division by default. Alternatively you could add this to the top of your script:
from __future__ import division
If you are sure that you only need to support Python 3 you can remove the float() and ignore the above.
As stated above by #idjaw, don't use list as a parameter instead use listr (for example). Your values = [list] is erroneous (also stated by #idjaw) and should be removed.
Also, according to PEP257, you should not use "(list) -> number" in your docstrings as that should only be used for builtins.
Finally, your loop should look like for l in listr: and then you add values to your mean variable. divide it by the number of values in the list and print the result.

Categories