How do i create a slice() object so that it would include the last element of a list/string
s = 'abcdef'
s[slice(2,4)]
works fine.
Say I wanted to get elements from second to the end, the equivalent of s[2:]
s[slice(2)] # only gives first two elements, argument is interpreted as the end of the range
s[slice(2,)] # same as above
s[slice(2, -1)] # gives a range from second to the end excluding the last element
s[slice(2, 0)] # gives empty as expected, since end of range before the start
I can get specifically the last element with slice(-1, -2, -1), this won't work correctly for more then one element.
If you want to include the last element you can do that in the following two ways :
s[slice(2,6)]
or replace 6 with len(s)
Or you could also do:
s[slice(2,None)]
You can test it with magic method __getitem__. The last object can be get with slice(-1, None, None):
s = 'abcdef'
class A:
def __getitem__(self, v):
print(v)
a = A()
a[-1:]
print("s[-1:] = ", s[-1:])
print("s[slice(-1, None, None)] = ", s[slice(-1, None, None)])
Prints:
slice(-1, None, None)
s[-1:] = f
s[slice(-1, None, None)] = f
Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want last element in list, use -1 as index.
So you can just use:
s= "abcdef"
print(s[-1])
Result:
f
Related
I should replace the last element of a tuple in a list of tuples with and object given as input and I tried to write this code but I got a "list assignment index out of range" error at line 4. How should I fix it?
def replaceLast (tupleList, object):
for i, tup in enumerate(tupleList):
lis = list(tup)
lis[-1] = object
tupleList[i] = tuple(lis)
return tupleList
lT=[(1,),(2,3),(),(7,3)]
replaceLast(lT,11) #=> [(11,), (2, 11), (11,), (7, 11)] -> this should be the result
The problem is the empty tuple in your list lT, which does not have a last element, therefore you cannot access it with lst[-1].
Instead of changing lists, create new ones:
def replace_last(tuples, object):
return [
tup[:-1] + (object, )
for tup in tuples
]
your issue is generated when you have empty tuple, then your variable lst will be an empty list so will not make sense to use lst[-1], this will generate your error, a simple fix will be to check if is an empty list:
if lst:
lst[-1] = object
else:
lst.append(object)
Suppose I have a string value str=xxx. Now I want to replace it via multi-index, such as {(1, 3):'rep1', (4, 7):'rep2', (8, 9):'rep3'}, without disturbing the index order. How can I do it?
Pseudo-code (in Python 2.7):
str = 'abcdefghij'
replacement = {(1, 3):'123', (4, 7):'+', (8, 9):'&'} # right index isn't include
# after some replacements:
str = some_replace(str, replacement)
# i want to get this:
print str
# 'a123d+h&j'
# since string is immutable, make a list out of the string to modify in-place
lst = list(str)
Use slice to modify items, a stronger explanation about slice and assignment can be found here; slice(*k) creates a slice object from the keys of the replacement. For instance, slice(*(1, 3)) gives a slice of slice(1, 3) which is equivalent to lst[1:3] when used as index, and replaces the corresponding elements with the corresponding value when the assignment on the slice is called:
# Here sort the index in reverse order so as to avoid tracking the index change due to the
# difference of the sizes between the index and replacement
for k, v in sorted(replacement.items(), reverse=True):
lst[slice(*k)] = v
''.join(lst)
# 'a123d+h&j'
Can anyone explain what is going on here as I am flummoxed
I have a module-wide list variable with elements that have fields - mylist with 'n' entries, each of field1, field2..fieldx
I want to access them in a procedure, so have (with some trace/debug statements)
print mylist [1].dataFieldCheckType
for lIndex, lField in enumerate(mylist, start = 1):
print lField.dataFieldCheckType
The first print statement gives the value -4 (which is correct), the second gives a different value, 0, over a simple one-statement step.
To my mind, lField is being created as a new element with default values but I do not know, nor understand, why. Why is the second print statement giving a different value from the first?
What am I doing wrong? Or, probably more pertinently, what am I not understanding?
I have asked this in another forum but no-one has come up with a plausible explanation.
In enumerate(), start does not specify the starting index into the iterable. It specifies the starting value of the count. enumerate() iterates over the whole iterable, from the first (index 0) to the last element, regardless of the start parameter.
The first print statement in your loop prints mylist[0].dataFieldCheckType, just as it ought to. You're just hoping it would be mylist[1].dataFieldCheckType.
If you want to take all elements of the list starting at the second (index 1), just slice it:
mylist[1:]
And if you really do need the index, too, combine the slice with enumerate():
enumerate(mylist[1:], start=1)
enumerate yields (index + start, value) tuples for every value of an iterable. The optional start parameter is used as an offset value to compute the first element of the generated tuples:
>>> a = ['hi', 'stack', 'overflow']
>>> for x in enumerate(a, -4):
... x
...
(-4, 'hi') # 0 + (-4)
(-3, 'stack') # 1 + (-4)
(-2, 'overflow') # 2 + (-4)
If you want to skip elements of an iterable, but don't need that particular slice in memory (all you want to do is iteration), use itertools.islice:
>>> from itertools import islice
>>> for x in islice(a, 2, None):
... x
...
'overflow'
Of course, you could combine the two for great justice.
>>> for x in islice(enumerate(a), 0, 2):
... x
...
(0, 'hi')
(1, 'stack')
What does for row_number, row in enumerate(cursor): do in Python?
What does enumerate mean in this context?
The enumerate() function adds a counter to an iterable.
So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively.
Demo:
>>> elements = ('foo', 'bar', 'baz')
>>> for elem in elements:
... print elem
...
foo
bar
baz
>>> for count, elem in enumerate(elements):
... print count, elem
...
0 foo
1 bar
2 baz
By default, enumerate() starts counting at 0 but if you give it a second integer argument, it'll start from that number instead:
>>> for count, elem in enumerate(elements, 42):
... print count, elem
...
42 foo
43 bar
44 baz
If you were to re-implement enumerate() in Python, here are two ways of achieving that; one using itertools.count() to do the counting, the other manually counting in a generator function:
from itertools import count
def enumerate(it, start=0):
# return an iterator that adds a counter to each element of it
return zip(count(start), it)
and
def enumerate(it, start=0):
count = start
for elem in it:
yield (count, elem)
count += 1
The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common for i, ... unpacking case and using a standard C integer value for the counter until the counter becomes too large to avoid using a Python integer object (which is unbounded).
It's a builtin function that returns an object that can be iterated over. See the documentation.
In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:
for item in enumerate(["a", "b", "c"]):
print item
prints
(0, "a")
(1, "b")
(2, "c")
It's helpful if you want to loop over a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate.
I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate instead.
I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable).
list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
letter = list_of_letters[i]
print (i, letter)
The output is:
0 a
1 b
2 c
I also used to do something, even sillier before I read about the enumerate function.
i = 0
for n in list_of_letters:
print (i, n)
i += 1
It produces the same output.
But with enumerate I just have to write:
list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
print (i, letter)
As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.
So if you have a list say l = ["test_1", "test_2", "test_3"], the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')].
Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).
for index, value in enumerate(joint_values):
if index == 3:
continue
# Do something with the other `value`
So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (i.e., joint_values[i]).
Although another user mentioned an implementation of enumerate using zip, I think a more pure (but slightly more complex) way without using itertools is the following:
def enumerate(l, start=0):
return zip(range(start, len(l) + start), l)
Example:
l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)
Output:
[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]
[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]
As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.
The enumerate function works as follows:
doc = """I like movie. But I don't like the cast. The story is very nice"""
doc1 = doc.split('.')
for i in enumerate(doc1):
print(i)
The output is
(0, 'I like movie')
(1, " But I don't like the cast")
(2, ' The story is very nice')
I am assuming that you know how to iterate over elements in some list:
for el in my_list:
# do something
Now sometimes not only you need to iterate over the elements, but also you need the index for each iteration. One way to do it is:
i = 0
for el in my_list:
# do somethings, and use value of "i" somehow
i += 1
However, a nicer way is to user the function "enumerate". What enumerate does is that it receives a list, and it returns a list-like object (an iterable that you can iterate over) but each element of this new list itself contains 2 elements: the index and the value from that original input list:
So if you have
arr = ['a', 'b', 'c']
Then the command
enumerate(arr)
returns something like:
[(0,'a'), (1,'b'), (2,'c')]
Now If you iterate over a list (or an iterable) where each element itself has 2 sub-elements, you can capture both of those sub-elements in the for loop like below:
for index, value in enumerate(arr):
print(index,value)
which would print out the sub-elements of the output of enumerate.
And in general you can basically "unpack" multiple items from list into multiple variables like below:
idx,value = (2,'c')
print(idx)
print(value)
which would print
2
c
This is the kind of assignment happening in each iteration of that loop with enumerate(arr) as iterable.
the enumerate function calculates an elements index and the elements value at the same time. i believe the following code will help explain what is going on.
for i,item in enumerate(initial_config):
print(f'index{i} value{item}')
I have a list of the following kind:
class Any(object):
def __init__(self,a,b):
self.a=a
self.b=b
l=[Any(1,3),Any(2,4),Any(1,2),Any(None,6),Any('hello',6), Any(1,'ChuckNorris'),Any(1,2)]
lis a list that contains only instances of Any. I'd like to find the position of the first of these instances which attribute a equals 'None`.
As my list is very long, the algorithm should not explore the whole list but it should stop as soon as the condition (in my example, attribute a equals None) is found.
In the above example the answer of this algorithm should be 3.
Use a generator expression and next:
next((i for i, item in enumerate(l) if item.a is None), None)
This would return None if no such item is found.
Demo:
>>> l=[Any(1,3),Any(2,4),Any(1,2),Any(None,6),Any('hello',6), Any(1,'ChuckNorris'),Any(1,2)]
>>> next((i for i, item in enumerate(l) if item.a is None), None)
3
try:
answer = next((val for val in enumerate(l) if val[1].a is None))[0]
except StopIteration:
# No element matching condition in sequence
answer = None
This creates a generator object, so it effectively only expands the element you are currently inspecting, and once you find a matching target, short circuits out of the iteration.