So I've been playing around with python and noticed something that seems a bit odd. The semantics of -1 in selecting from a list don't seem to be consistent.
So I have a list of numbers
ls = range(1000)
The last element of the list if of course ls[-1] but if I take a sublist of that so that I get everything from say the midpoint to the end I would do
ls[500:-1]
but this does not give me a list containing the last element in the list, but instead a list containing everything UP TO the last element. However if I do
ls[0:10]
I get a list containing also the tenth element (so the selector ought to be inclusive), why then does it not work for -1.
I can of course do ls[500:] or ls[500:len(ls)] (which would be silly). I was just wondering what the deal with -1 was, I realise that I don't need it there.
In list[first:last], last is not included.
The 10th element is ls[9], in ls[0:10] there isn't ls[10].
If you want to get a sub list including the last element, you leave blank after colon:
>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I get consistent behaviour for both instances:
>>> ls[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[10:-1]
[10, 11, 12, 13, 14, 15, 16, 17, 18]
Note, though, that tenth element of the list is at index 9, since the list is 0-indexed. That might be where your hang-up is.
In other words, [0:10] doesn't go from index 0-10, it effectively goes from 0 to the tenth element (which gets you indexes 0-9, since the 10 is not inclusive at the end of the slice).
It seems pretty consistent to me; positive indices are also non-inclusive. I think you're doing it wrong. Remembering that range() is also non-inclusive, and that Python arrays are 0-indexed, here's a sample python session to illustrate:
>>> d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d[9]
9
>>> d[-1]
9
>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> len(d)
10
when slicing an array;
ls[y:x]
takes the slice from element y upto and but not including x. when you use the negative indexing it is equivalent to using
ls[y:-1] == ls[y:len(ls)-1]
so it so the slice would be upto the last element, but it wouldn't include it (as per the slice)
-1 isn't special in the sense that the sequence is read backwards, it rather wraps around the ends. Such that minus one means zero minus one, exclusive (and, for a positive step value, the sequence is read "from left to right".
so for i = [1, 2, 3, 4], i[2:-1] means from item two to the beginning minus one (or, 'around to the end'), which results in [3].
The -1th element, or element 0 backwards 1 is the last 4, but since it's exclusive, we get 3.
I hope this is somewhat understandable.
Related
I found iterable functions, but I am not sure how I can use.
For example, skip, take, map, forEach, fold and join
Could you give me examples how to use?
Yes, let's check the following sample code.
List<int> values = [1, 2, 3, 4, 5, 6, 7, 8, 9];
print(values.skip(5).toList());
//[6, 7, 8, 9]
print(values.skip(5).take(3).toList());
//[6, 7, 8]
values.skip(5).take(3).map((e) => e.toString()).forEach((element) {print(element);});
//6 7 8
String str = values.fold("initialValue",
(previousValue, element) => previousValue + ", " + element.toString());
print(str);
//initialValue, 1, 2, 3, 4, 5, 6, 7, 8, 9
str = values.join(", ");
print(str);
//1, 2, 3, 4, 5, 6, 7, 8, 9
skip(1) skips the first value, 1, in the values list literal.
take(3) gets the next 3 values 2, 3, and 4 in the values list literal.
map() Returns a new lazy [Iterable] with elements that are created by calling f on each element of this Iterable in iteration order.
fork() Reduces a collection to a single value by iteratively combining each element of the collection with an existing value
join() Converts each element to a [String] and concatenates the strings.
Hi Avdienko and welcome to Stack Overflow. I will give you an example for a .forEach iterable function performed on a List.
List<int> listOfIntegers = [1, 2, 3, 4, 5];
listOfIntegers.forEach((element) {
print(element.toString() + " ");
});
This code will result in printing "1 2 3 4 5 " to the console.
I'm trying to remove every nth number from a list in a for loop, but something's gone wrong
There's a variable that determines what numbers to remove
If I had a list of 1 to 10, and I tried removing every second number, and then third
I should get 1, 3, 5, 7, 9 after removing every second number,
and 1, 3, 7, 9 after removing every third (only one number)
for i in range(repeatAmount):
multiple = int(input())
del numberVar[1::multiple]
print(numberVar)
This code returns [1, 3, 5, 7, 9] after removing every second number, which is correct
But then returns [1, 5, 7] after removing every third number
I have no idea what's going wrong
Change this line
del numberVar[1::multiple]
to this line:
del numberVar[multiple-1::multiple]
Output: [1, 3, 7, 9]
In your loop, you referenced index #1 both times as your starting index, hence you removed the first and fourth elements (3 and 9) in the second iteration of the loop.
I am looking for a fast implementation of the following code; using, for instance, map() or next():
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
total_so_far = 0
for i in l:
total_so_far += i
if total_so_far > 14:
break
print(i)
The code prints the index of item in list where sum of start of list to the index is greater greater than 14.
Note: I need to continuously update the link in another loop. Therefore, a solution in numpy would probably be too slow, because it cannot update a list in-place.
You can also make use of itertools.accumulate() together with enumerate() and next():
In [1]: from itertools import takewhile
In [2]: l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]: next(index for index, value in enumerate(accumulate(l)) if value > 14)
Out[3]: 5
possible_list = []
bigger_list = []
new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]
for i in range(0,len(new_list)):
# if the next index is not greater than the length of the list
if (i + 1) < (len(new_list)):
#if the current value is less than the next value
if new_list[i] <= new_list[i+1]:
# add the current value to this sublist
possible_list.append(new_list[i])
# if the current value is greater than the next, close the list and append it to the lager list
bigger_list.append(possible_list)
print bigger_list
How do I find the longest consistent increment in the list called new_list?
I expect the result to be
[[0,2], [2], [1,14], [1,14], [1,4,6,6,7], [0,10,11]]
I can find the remaining solution from there myself.
One problem (but not the only one) with your code is that you are always adding the elements to the same possible_list, thus the lists in bigger_list are in fact all the same list!
Instead, I suggest using [-1] to access the last element of the list of subsequences (i.e. the one to append to) and [-1][-1] to access the last element of that subsequence (for comparing the current element to).
new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]
subseq = [[]]
for e in new_list:
if not subseq[-1] or subseq[-1][-1] <= e:
subseq[-1].append(e)
else:
subseq.append([e])
This way, subseq ends up the way you want it, and you can use max to get the longest one.
>>> subseq
[[0, 25], [2], [1, 14], [1, 14], [1, 4, 6, 6, 7], [0, 10, 11]]
>>> max(subseq, key=len)
[1, 4, 6, 6, 7]
Basically, wanted to iterate over a list of numerical data to change it's contents, where the numerical at the start of the list is moved to the last, and then the data is shifted to the left. Whilst I have achieved this, as the printed contents of the loop gives the desired results, when trying to append the contents of said loop to said dictionary, it only does this for the final iteration. Here's my code:
minor=[1,2,3,4,5,6]
MNP = {'scale degree' : []
}
def patterns(scale):
for i in scale:
print (scale)
scale.insert(len(scale),scale[0])
del(scale[0])
MNP['scale degree'].append(scale)
using the function patterns, this is the output:
>>> patterns(minor)
the list, minor, is at the top of the page by the way.
output:
[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6, 1]
[3, 4, 5, 6, 1, 2]
[4, 5, 6, 1, 2, 3]
[5, 6, 1, 2, 3, 4]
[6, 1, 2, 3, 4, 5]
Yet when I try to print the contents of the list, scale degree, in the MNP dict, the result is:
MNP['scale degree']
[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]
I am very perplexed by this result, it's as if the output changes depending on the operation called upon it?
Thank you for any help in advance. It's also worth noting that I've been stuck with this for a good amount of time, so if there's any resources out there that may help me understand similar occurrences i certainly wouldn't pass that up.
The reason this happens is because what you store in MNP['scale degree'] is only a reference to scale. So when you change scale, so do the entries in MNP['scale degree']. What you need to do to avoid this is copying scale each time you append it (i.e. creating a new list instead of adding a reference). You can do this with the copy module:
import copy
minor=[1,2,3,4,5,6]
MNP = {'scale degree' : []
}
def patterns(scale):
for i in scale:
print (scale)
scale.insert(len(scale),scale[0])
del(scale[0])
MNP['scale degree'].append(copy.copy(scale))
patterns(minor)
print(MNP['scale degree'])