+ 2
How to 'slice' in other languages than Python?
In Python you can do things that are wildly convenient, like cramming objects of all types dynamically in a 'list', embedded whichever way you like. When I want to do something similar in, let's say, C++, I usually feel like with ball and chain. Yet it is somehow, teeth-grindingly, possible to do without lists. But another thing I really miss is slicing! In Python you can jump your way through every iterable with 'enhanced indexing' like [5:7], [-5:-1], [7: 3: -2] and so on. How can one live without this? What are the typical, idiomatic, not brief but briefish ways to reuse parts of iterables, reversing them, jumping around within them and so on? I'd be happy if those fluent in C-like languages gave a few examples.
11 Antworten
+ 4
"Maybe just write: 'for (int i=5; i<10;i+=2)'?"
Sure! I was creating a new array b, so I used its indices. But if you just want to do stuff with a, that is the better option.
+ 3
Couldn't you just create the sliced array using a for loop? For example, instead of b = a[5: 10: 2], we can use
for (i=0; i<3; i++) {
b[i] = a[5 + 2*i];
}
+ 3
Let's say y is a list of length n. Then
if x is in y:
# do this
is equivalent to
for (int i=0; i<n; i++) {
if (x==y[i]) {
// do this
break;
}
}
There may be ways to shorten these things in C++, Java, and JS. But probably not in C.
+ 2
Yeah, I've been wondering if for-ing through everything was the only solution.
But as you write it down, it suddenly doesn't look all that long. Longer, but manageable.
Maybe just write: 'for (int i=5; i<10; i+=2)'?
Okay, well yeah, could we then consider Python's slicing as a sort of list comprehension?
+ 2
Ah, I see... sorry, my sloppy reading!
Good to see the two applications side by side.
I am now experiencing one issue with starting with a language like Python: You can do a lot of stuff easily, but as soon as you leave Python, it feels a bit like starting from scratch. While when you go from C to Python, it probably feels more like an abbreviation of what you already know.
+ 2
I have another area where I wonder how to realize it in Cish languages shortishly:
All these situations where you use 'in', like do this if x in y else do that etc.
+ 2
Kishalaya Saha You edited this 4 times🤔! I was observing for a while😁. You are good editor and even keep track of it👍
Anyway my sequence is coming soon, if you have not already been 😴😴
+ 2
slice is also a class, for example
[3:100:3] == [slice(3,100,3)]
with this method, it can also be used in other languages😀
+ 1
Roneel, I agree, you learn to think about the 'what' without needing too much energy for the 'how'.
Later you can extend (but have to handle some frustration).
+ 1
Thank you, Kish!
Seems like in C a lot can (must) be done with for loops.
It's less convenient, but not impossible ...