How to check the last element of a python list? - python

In python I need a stack, and I'm using a list for it. In the documenation it says that you can use append() and pop() for stack operations but what about accessing the top of the stack without removing it?
How to do that in the most readable way? Because all I came up with is stack[-1:][0] which looks a bit ugly for me, there must be a better way.

No need to slice.
stack[-1]

stack[-1] ist the last element
EDIT renamed the previously list called variable (Thanks, Tim McNamara).

Related

How to slice a string in reverse in Python?

I understand how to normally slice a string and reverse it, but don't get how to do both simultaneously.
Let's say
message="hi there"
And I wanna select only the "there" part and reverse it, so the output will be "ereht".
Is there a way to do it? Preferably using only the "message" variable, but any other ways are ok, too.
You would split the string and then reverse it part you desire
rev = message.split()[-1][::-1]
This solution will also work for the example given in the OP (credit to Kelly Bundy):
rev = message[:-6:-1]
For your specific question, you can use this:
message.split()[-1][::-1]
You just need to select the second slice with [1] and then reverse it using [::-1]
message.split()[1][::-1]

While loops where only conditions are executed? [duplicate]

This question already has answers here:
Remove all occurrences of a value from a list?
(26 answers)
Closed 2 years ago.
So I want to execute only while loop statements, without putting anything inside them. For example, I have an array arr from which I have to remove multiple occurrences of some element. The instant the condition statement returns an error, while loop should end.
arr=[1,2,4,2,4,2,2]
This removes only one 2:
arr.remove(2)
I need to run this as long as it does not return error. (C++ has a semicolon put after while to do this).
I want something like this
while(arr.remove(2));
Three things.
First, it's not considered good practice in Python – it's not "pythonic" – to use an expression for its side effects. This is why, for example, the Python assignment operator is not itself an expression. (Although you can do something like a = b = 1 to set multiple variables to the same value, that statement doesn't break down as a = (b = 1); any such attempt to use an assignment statement as a value is a syntax error.)
Second, modifying data in place is also discouraged; it's usually better to make a copy and make the changes as the copy is constructed.
Third, even if this were a good way to do things, it wouldn't work in this case. When the remove method succeeds, it returns None, which is not truthy, so your loop exits immediately. On the other hand, when it fails, instead of returning a false value, it throws an exception, which will abort your whole program instead of just the loop, unless you wrap it in a try block.
So the list comprehension probably is the best solution here.
The way you are looking to solve this does not yield the results you are looking for. Since you are looking to create a new list, you are not going to want to use the remove function as per #Matthias comment. The idiomatic way to do it would be something along the lines of this:
arr=[1,2,4,2,4,2,2]
arr = [x if x != 2 for x in arr]
So I want to execute only while loop statements, without putting anything inside them.
That's really not necessary. Don't try to copy other language's syntax in Python. Different languages are designed with different objectives and hence, they have different syntax (or grammar of the language). Python has a different way of doing things than C++.
If you want to focus on the effectiveness of the program, then that's the different story. See this for more information on this.
Unfortunately, remove doesn't return anything (it returns None). So, you can't have anything that would look neat and clean without putting anything inside while.
Pythonic way to remove all occurrence of a element from list:
list(filter((2).__ne__, arr))
Or
arr = [x for x in arr if x != 2]
Or
while 2 in arr:
arr.remove(2)
you can use:
arr = [1,2,4,2,4,2,2]
try:
while arr.pop(arr.index(2)):
pass
except ValueError:
pass
print(arr)
#[1, 4, 4]
I am assuming you want to remove all occurrences of an element. This link might help you.
click here

How to change List parenthesis from [] to none

short Question in Code:
i=0
k_start[i]
[8515]
i=1
k_start[i]
139253
How can i avoid the parenthesis in this example? Or Why at least do they appear with when i is 0?
Edit: Sorry for this bad Question, the problem was that i had a list of lists.
I'm not sure why your first element is coming out as a sub-list but you can get rid of the brackets (in this one specific case) by calling k_start[0][0]... Try printing k_start to see what the whole array looks like. That way you can see what is happening and perhaps find a more general solution. It's hard to do from the outside without more info, such as upstream code or a printout of the array.

simple python list comprehension question

i am trying to select the elements of a list without the very first element. the following code works but it kinda look ugly to me
[s[i] for i in range(len(s)) if i>0]
is there a better way to write it? thanks
Use the slicing notation:
s[1:]
Alternatively, you can avoid copying the list thus:
itertools.islice(s, 1, None)
The result isn't a list — it doesn't support random access, for instance — but you can pass it to anything that accepts an iterator.
Wouldn't s[1:] be correct?

Can you iterate a number backwards without using a list?

How would you iterate a number backwards without using a list in Python 3?
Using lists, I would probably do something like:
li = list(range(100))
for i in li[::-1]:
print(i)
This is a fine solution, but it does not work with huge numbers.
Right now, I'm trying to iterate a number backwards with large numbers, but an overflow error happens, so I think I need to somehow find a way to iterate a number backwards without using lists.
Is there any way?
Iterators that provide the __reversed__() special method also support reversed iteration. In Python 3.x, range() iterators have this method, so you can also use
for i in reversed(range(100)):
print(i)
In Python 2.x, xarnge() allows reversed iteration:
for i in reversed(xrange(100)):
print i
Both versions do not store the whole list in memory.
Generally? No. Python's iterator protocol only supports forward iteration.(Edit: This turned out to be incorrect, see Sven Marnach's answer.)
However, you can reverse range(n, m): range(m-1, n-1, -1) (the -1 are ugly, yes, but it's necessary due to range returning a half-open range).
for i in range(10,0,-1):
print(i)
Try using range]and step down...
for i in range(100, 0, -1):
[update] I just noticed that you said Python 3, in which case you can just use range instead of xrange.

Categories

Resources