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?
Related
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]
i needed a list of only one tuple, like this[(1,2,3,4,5,6)]
, i tried this,
>>> [( i for i in range(1,10))]
[<generator object <genexpr> at 0x7fbf7ad94cd0>]
what is that generator object? How to use it?
how to generate this kind of list?
You need this:
[tuple( i for i in range(1,10))]
(i for i in something) notation is called Generator expression in Python and returns a generator object. You are simply, capturing this object in list. See PEP-289, for more knowledge on Generator Expressions
Also, I am assuming, you plan to do much more than i for i in range(1,10), as this is completely redundant, you can just as well do [tuple(range(1,10))]
I'm new to python and this is just to automate something on my PC. I want to concatenate all the items in a list. The problem is that
''.join(list)
won't work as it isn't a list of strings.
This site http://www.skymind.com/~ocrow/python_string/ says the most efficient way to do it is
''.join([`num` for num in xrange(loop_count)])
but that isn't valid python...
Can someone explain the correct syntax for including this sort of loop in a string.join()?
You need to turn everything in the list into strings, using the str() constructor:
''.join(str(elem) for elem in lst)
Note that it's generally not a good idea to use list for a variable name, it'll shadow the built-in list constructor.
I've used a generator expression there to apply the str() constructor on each and every element in the list. An alternative method is to use the map() function:
''.join(map(str, lst))
The backticks in your example are another spelling of calling repr() on a value, which is subtly different from str(); you probably want the latter. Because it violates the Python principle of "There should be one-- and preferably only one --obvious way to do it.", the backticks syntax has been removed from Python 3.
Here is another way (discussion is about Python 2.x):
''.join(map(str, my_list))
This solution will have the fastest performance and it looks nice and simple imo. Using a generator won't be more efficient. In fact this will be more efficient, as ''.join has to allocate the exact amount of memory for the string based on the length of the elements so it will need to consume the whole generator before creating the string anyway.
Note that `` has been removed in Python 3 and it's not good practice to use it anymore, be more explicit by using str() if you have to eg. str(num).
just use this, no need of [] and use str(num):
''.join(str(num) for num in xrange(loop_count))
for list just replace xrange(loop_count) with the list name.
example:
>>> ''.join(str(num) for num in xrange(10)) #use range() in python 3.x
'0123456789'
If your Python is too old for "list comprehensions" (the odd [x for x in ...] syntax), use map():
''.join(map(str, list))
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).
What is the best way to do the following in Python:
for item in [ x.attr for x in some_list ]:
do_something_with(item)
This may be a nub question, but isn't the list comprehension generating a new list that we don't need and just taking up memory? Wouldn't it be better if we could make an iterator-like list comprehension.
Yes (to both of your questions).
By using parentheses instead of brackets you can make what's called a "generator expression" for that sequence, which does exactly what you've proposed. It lets you iterate over the sequence without allocating a list to hold all the elements simultaneously.
for item in (x.attr for x in some_list):
do_something_with(item)
The details of generator expressions are documented in PEP 289.
Why not just:
for x in some_list:
do_something_with(x.attr)
This question is tagged functional-programming without an appropriate answer, so here's a functional solution:
from operator import itemgetter
map(do_something_with, map(itemgetter('attr'), some_list))
Python 3's map() uses an iterator, but Python 2 creates a list. For Python 2 use itertools.imap() instead.
If you're returning some_list, you can simplify it further using a generator expression and lazy evaluation :
def foo(some_list):
return (do_something_with(item.attr) for item in some_list)