How to add one to he last value in a list Python - python-3.x

Im fairly new to python and want to know how to add one to the last value in a list such as [1,5,9] or [44,45,20] I know it needs a for loop somewhere but how?

you can do this my_list[-1] += 1 .
the negative index let you start from the ending of a list (or any other iterable object), so -1 index is the last element in your list.

If by "adding" you mean arithmetic addition (i.e. +), do:
mylist[-1] += 1
If by "adding" you mean appending a new item to the list, do:
mylist.append(1)

Related

Pythonic way to find lowest value in dictionary with list as values

I have a dictionary with values as list. In the given dictionary I want to find the lowest number (for every item in the list considering the value at index 0). I have written a script and works fine, but I am looking for a more Pythonic way to solve this.
c={'Apple': ['210-219', '246-255'], 'Orange': ['159-161', '202-204', '207-209', '209-211', '220-222', '238-240', '245-247', '261-263']}
loweststart=[]
for ckey, cvalue in c.items():
for i in cvalue:
print (i.split('-')[0])
start=int(i.split('-')[0])
loweststart.append(start)
print (loweststart)
print ('The lowest:',min(loweststart))
A pythonic way:
min_list = [int(element.split('-')[0]) for value in c.values() for element in value]
print(min(min_list))
You can use the min function with a generator expression that iterates through the items in the sub-lists of the dict and outputs the integer values of the first tokens in the strings:
min(int(s[:s.find('-')]) for l in c.values() for s in l)
Using a generator expression is more efficient because it avoids the need to create a temporary list to store all the values extracted from the sub-lists.
As much as I hate the adjective Pythonic, this would seem to qualify:
min([min([int(i.split('-')[0]) for i in ci[1]]) for ci in c.items()])
(The logic is slightly different than the original, in that it finds the minimum of each list, then the minimum of those minima, but the end result is the same.)

Is there a way to get increment counter from a Python 'for' loop with decrement range?

I read everyone uses enumerate, but I don't think I know how to use it in my code. I want to print the value of an alphabet in a string according to alphabet order and the next character will increment the value by 1 and I want to start it from the last character in the string.
I can solve the code, but how can I replace the counter i without using i = i+1 to make this code a bit shorter? Is there a way to implement something in the for loop?
This is my code:
def project(r):
i = 0
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+i)
i=i+1
project(str(input()).lower())
For example, if I insert a string such as "sad", the output will be [4,2,21] because d = 4, a = 1, s = 19.
Is there a way to implement the counter without initializing i?
According to your question what I can understand is you want to use enumerate to get your result.
You can simply do as below:
def project(r):
for (i, char) in enumerate(r, 0):
print(ord(r[-i-1])-96+i)
project(str(input()).lower())
And the enumerate() method adds a counter to an iterable and returns it in a form of an enumerate object.
Syntax: enumerate(iterable, start)
Here 0 is the default value of start which you can give according to your requirement. For example, if you want your counter to start from 100, then you can do like enumerate(iterable, 100).
In the above code, I have used enumerate() function and initialized the counter from 0 and as you want to display from the last, I used -ve index to get the last item in a list.
And as I initialized the counter 0 so how can I get the items from last? For that, I subtract the index by -1 like r[-i-1]. So for the first iteration the i value becomes 0, so r[-i-1] becomes r[-0-1] which is r[-1] and on the second iteration, i becomes 1, so r[-i-1] becomes r[-1-1]which isr[-2]` which result second last item. Similarly it goes on.
For more information about enumeration, please check the below link so you can get a clear idea.
Python enumerate()
13. Enumerate
Dcoder14, actually I want to make my code a bit shorter. Even there is a way other than enumerate, but still thank you very much... I used your code, but I edited it a little bit to make it one line shorter...
This is my code:
def project(r):
for (i, char) in enumerate(r, 0):
print(str(ord(r[-i-1])-96+i))
project(str(input()).lower())
If you want to make it shorter, you can use the decrement char value since we can get an increment by subtracting the length of the string (input) with char in the for loop.
For example, this is my code:
def project(r):
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+(len(r)-char))
project(str(input()).lower())

Why is this iteration not updating the count?

I am writing a function that takes two strings as parameters, turns them in lists, and then returns an index of where the two strings differ:
def ss(line1,line2):
count = 0
list1 = line1.split()
list2 = line2.split()
for word in list1:
if word is not list2[count]:
return count
else:
count += 1
ss("Why is this not working?", "Why is this not working?")
The output I get is that my count is whatever I set it to initially (e.g., "0"). As far as I can see, it should be updating the count and then reiterating through the lists to compare the next indexes?
What do I not understand about how for-loops work?
Thanks.
The issue is that you are using != instead of is not.
Explanation:
The is keyword in Python compares object identity. Every string in Python is it's own separate object and thus, it's own separate identity. So when you use the is keyword with two strings it will not check the actual contents.
However, to compare the contents of an object or variable you can use == or != which return True or False.
I hope this answer helped you and if you have any further questions please feel free to post a comment below!

Getting a "list index can't be a float" error when i use the same iterator from a loop in an if statment in Python 3.4

I try to iterate through a list and check each value if it is a negative number, using the following code :
for i in listy:
if (listy[i]<0):...
For some reason, python tries to evaluate listy[0.5]<0, which is the 1st item on the list. How can I fix this ?
i is the value not the index.
This line is not what you want (listy[i]<0).
You probably meant to do i<0
(listy[i]<0) is trying to use the value as the index. In you list the value is a float which can't be used as an index.
If you really want to use the index you could do:
for i in range(len(listy)):
if listy[i] < 0:
#do something
In C and many other languages, you often use the length of an array when iterating through it. You can do this in Python as well but you can also iterate through the elements without explicitly using the index (position). You seem to be mixing the two approaches and therefore you get an unexpected result.
This will iterate through the values only:
for i in listy:
# here, i is the value of the list entry
print(i)
This will use the length of the list and the index (position):
for i in range(len(listy)):
# here, i is the index (position) of the list entry, not the value
print(listy[i])
This will give you both index and value:
for i, val in enumerate(listy):
# here, i is the index (position) and val is the value
print(i, val)

Change list elements to a string with spaces in Prolog

In Prolog, if I am taking a list such as [hello,this,is,a,sentence] as a parameter for a predicate, how do I get a return value Y such that it will return that list as a string with spaces? e.g. [hello,this,is,a,sentence] will return hello this is a sentence.
makesentence([H|T],Y):- % some code here
I was able to run through the list recursively and have Y return the same list input with this:
makesentence([],[]). % base case returns an empty list
makesentence([X],[X]). % one list element returns that element in a list
makesentence([H|T],Y):- % a list of more than one element
makesentence(T,Result), % recursively call function on the tail
append([H],Result,Y). % append the head to the rest of the list
But when I try to make the output without a list and with spaces I faulter. I have tried this:
makesentence([],'').
makesentence([X],X).
makesentence([H|T],Y):-
makesentence(T,Result),
append(H,Result,Y).
I think it has to do with the fact the append predicate in Prolog only deals with appending a list, but I am unsure. How would I procede? Thanks in advance.
SWI-Prolog has a specialized built-in for that: atomic_list_concat/3
?- atomic_list_concat([hello,this,is,a,sentence],' ',A).
A = 'hello this is a sentence'.
figured it out with the help of Daniel. To put a list into a string with spaces use atomics_to_string/3. In my case:
makesentence([X],X).
makesentence([H|T],Y):-
makesentence(T,Result),
atomics_to_string([H,Result],' ',Y).
In the line atoms_to_string([H,Result],' ',Y)., the first parameter is the list, the second is what I want to add in between each entry, in this case a space ' ' and the third parameter is the assignment of the output, which in my case is Y. Thanks to Daniel for pointing me in the right direction.

Resources