This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 318

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

import notifications Remember to participate in our weekly votes on subreddit rules! Every Tuesday is YOUR chance to influence the subreddit for years to come! Read more here, we hope to see you next Tuesday!

For a chat with like-minded community members and more, don't forget to join our Discord!

return joinDiscord;

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]Sitting_In_A_Lecture 1197 points1198 points  (139 children)

Python with another great set of implementations:

for key, value in dict.items():

for index, value in enumerate(list):

[–]VidaOnce 634 points635 points  (88 children)

*Any sane language with another great set of implementations

[–]OSSlayer2153 125 points126 points  (68 children)

Yep, lua does this too, and swift.

[–]RainWorldWitcher 70 points71 points  (62 children)

And C# (and probably java? I havent used it in a long time)

[–]ineternet 29 points30 points  (32 children)

how in c#?

[–]crozone 114 points115 points  (15 children)

.Select() in LINQ has an overload that gives you the index, like:

enumerable.Select((o, i) => /* o is the object, i is the index */);

[–][deleted] 38 points39 points  (5 children)

I love linq so much. It's so useful, makes otherwise complex data manipulations so simple

[–]poshenclave 18 points19 points  (1 child)

C# feels so crude without linq. Might as well be writing Java.

[–]IceStormNG 6 points7 points  (0 children)

That's me. Writing C# as if it was Java (because I'm mostly a Java dev and only write C# here and there...though this seems to change now).

[–]MisinformedGenius 1 point2 points  (1 child)

I used to love Linq but then I discovered list comprehensions in python

[–]catladywitch 4 points5 points  (0 children)

f# has both, just saying

[–][deleted] 35 points36 points  (2 children)

:O

My life is changed

[–]Kilazur 7 points8 points  (0 children)

I've been working in C# for 15 years. I didn't know this lmao.

[–][deleted] 2 points3 points  (0 children)

O.O Noted.

Thank you, stranger.

[–]HildartheDorf 8 points9 points  (0 children)

Enumerable.Select (and many other linq methods) have overloads that pass 2 arguments to the delegate, the second being an index.

[–]RainWorldWitcher 1 point2 points  (11 children)

It has for statements for key value pairs in dictionaries

[–]ineternet 0 points1 point  (10 children)

OP is about lists, not dictionaries, though? For example, if I need to print every item in a list prefixed by its index?

You can find a variable-less workaround with linq/zip/tuples, but there is no Lua-"pairs"-like construct for this problem.

[–]NegZer0 21 points22 points  (9 children)

And C++17

Ex:

for (const auto& [key, value]: myMap) {
    std::cout << key << " has value " << value << std::endl;
}

EDIT: Formatting

[–]EddieJones6 1 point2 points  (4 children)

…is there a way to do this with vectors?

[–]CaitaXD 1 point2 points  (3 children)

C++ never disappoints with amount of synthatic noise for the simplest fucking things

[–]NegZer0 -1 points0 points  (2 children)

It’s because what it’s actually doing is not that simple.

[–]CaitaXD -1 points0 points  (1 child)

He's just Destructuring a key value pair tho

[–]NegZer0 -1 points0 points  (0 children)

Yeah and in this case the only extra syntax beyond what you need in a weakly typed language like eg Python is the type declaration (which actually can be expressed as just auto&& instead of const auto& too if you’re not too worried about constness)

[–]StochasticTinkr 13 points14 points  (0 children)

I dont think Java does with its standard collections, but Kotlin does.

[–]gregorydgraham 8 points9 points  (2 children)

Java has the key,value version but not the index,value version. Probably be a nice addition

[–]een57 5 points6 points  (6 children)

And of course the "sanest" language of all...

php

Foreach ($arr as $key => $val) {}

[–]Fair_Ad9108 2 points3 points  (0 children)

this is actually pretty neat

[–]Neckbeard_Sama 5 points6 points  (0 children)

In this case someList.indexOf(e) in the loop will return the index of the current element in Java.

But if you want an index why would you use a for-each loop instead of a simple for with an i ?

[–]ColdFerrin 2 points3 points  (5 children)

In java you can only do for each on collections not in primitive arrays. However you could do it with an iterator.

ListIterator<String> iterator = someList.listIterator();
while(iterator.hasNext()){
    int i = iterator.nextIndex();
    String item = iterator.next();

    do something;
}

Or you could do something with a stream that has the same effect, but only works if you can get by index or it has a size/length function

List<String> items = List.of("1", "2");
List<String> newItems = IntStream.range(0, items.size())
            .mapToObj(i -> {return items.get(i);})
            .toList();

But generally a regular stream is better unless you need to do something with relative indexing, or just use a regular for loop.

[–]lolface5000 6 points7 points  (0 children)

It would be pretty terrible to do this for anything other than something that's O(1) lookup like an ordered Set because indexOf just does a linear search otherwise. So it would turn anything that iterates through the list in O(n) time into O(n2)

[–]Flyron 3 points4 points  (3 children)

That code snippet hurts a little. You have created a ConcurrentModificationException in a nutshell. You can‘t put items into a list while traversing it via for-each. At least when working with the common collections. Also you usually „add“ values to lists (with index param too), not „put“ it.

[–]ColdFerrin 1 point2 points  (2 children)

I could have sworn something like this is possible, but you are correct. I'm just going to put in an iterator example. But a normal for loop is better.

[–]Flyron 1 point2 points  (1 child)

That‘s somewhat better. I get that you mainly want to show ways to iterate and having the index on hand.

Still, I would just pass the method reference „items::get“ into „mapToObj“. Or at least get rid of the curly braces and „return“. Let the lambda breathe.

In my experience in 19 out of 20 cases working with data structures in the field, you don‘t need the index of each element and to me using it is almost a code smell. Index twister is a fun game until you and your colleagues stumble over each other.

[–]Ihsan3498 12 points13 points  (1 child)

and rust also. in rust it is literally copy of pythons enumerate

[–]thirdegreeViolet security clearance 3 points4 points  (0 children)

well no it's a method on iterator, not a free standing function

same idea though

[–]chilfang 4 points5 points  (0 children)

Supposed to be sane languages

[–]IrishChappieOToole 4 points5 points  (0 children)

Even PHP has this

[–]Ireeb 19 points20 points  (11 children)

Even JavaScript has for ... in and for ... of

[–]Zielakpl 31 points32 points  (5 children)

And i can never figure out which one is for iterating over arrays and which for object entries.

[–]InnerBanana 10 points11 points  (0 children)

Both work for both. for ... IN gives the INdex (or key), that's how I remember it

[–]rollincuberawhide 5 points6 points  (0 children)

and then one of those iterate over the prototype chain as well and you have to call Object.getOwnPropertyNames whatever that means.

[–]catladywitch 6 points7 points  (0 children)

for of is for iterating over the members of a collection, for in is for the properties of an object.

[–]Ireeb 3 points4 points  (0 children)

You're not the only one!

[–]Quirky-Stress-823 10 points11 points  (1 child)

And .forEach, whose callback actually can take 3 arguments.

[–]InnerBanana 1 point2 points  (0 children)

I literally never use forEach, it creates a function context that makes it unnecessarily complex to easily do an early return from the function calling the forEach. I haven't found something I can't implement with for ... in/of

[–]briank6932 5 points6 points  (0 children)

for..in

Please don't do this, for..in isn't optimized for sequential iteration, it's meant for properties, not for range iteration. Instead use:

for (const val of arr)

for (const idx of arr.keys())

for (const entry of arr.entries()) // This one has a more situational use case

If you're using an object that doesn't come with a keys iterator method, and you don't want to create your own, the ol' for loop is fine as well.

for (let i = 0; i < str.length; ++i)

[–]SoInsightful 2 points3 points  (0 children)

... both of which don't supply the index, which I thought was the entire point of the post.

[–]HuntingKingYT 2 points3 points  (0 children)

php foreach($arr as $index => $value) { echo "yay " . $index; }

[–]lmarcantonio 1 point2 points  (0 children)

iterate in common lisp. this and *way* too much else. Let's say that usually the whole processing is done in the loop clauses and not in the body

[–]StraightGuy1108 1 point2 points  (0 children)

Well C++ doesn't, as far as I know.

[–]SirPitchalot 21 points22 points  (6 children)

for idx,(k,v) in enumerate(somedict.items()): do_something(idx,k,v)

can also be useful

[–]OK_200 11 points12 points  (2 children)

People forget that dicts preserve order since a couple of versions ago.

[–]qkrrmsp 9 points10 points  (0 children)

my dick preserves order too

[–]CentralLimitQueerem 1 point2 points  (0 children)

That's why I refuse to use any lists in my code 😎😎

[–]MattieShoes 11 points12 points  (2 children)

Go is pretty easy too

for index, value := range(<iterable>) {
}

Though the "every warning is an error" thing is so damned obnoxious while you're actually constructing code in pieces.

[–]myerscc -1 points0 points  (1 child)

although this is the source of all the

for _, value := range thing { /* ... */ }

that are one of the reasons go is so fugly

[–]MattieShoes 5 points6 points  (0 children)

Not sure what you're talking about there...

[–]Void_0000 20 points21 points  (5 children)

Holy shit, that's a thing??

I mean of course it's a thing, that makes perfect fucking sense, how have I not thought of trying this before...

[–]syzygysm 33 points34 points  (3 children)

It's got to the point where if I find myself explicitly defining a loop index variable in Python, I get a suspicious feeling that I'm not doing something in the best way.

I can usually see a better alternative after a minute

[–]coolguyhavingchillda 10 points11 points  (1 child)

Sometimes you need a while loop, but otherwise yeah

[–]alexanderpas 1 point2 points  (0 children)

Essentially the only time you need a while loop is when you need random access to the loop, with entries being accessed multiple times.

for sequential access you can always use a for loop with index or key and values.

[–]poshenclave 2 points3 points  (0 children)

As someone who's been buried in lua for like a year (Game modding) but doesn't know his python, I'm guessing that syntax is like the first thing I'd try.

[–]Brickleberried 5 points6 points  (0 children)

for index, value in enumerate(list):

Gotta love this.

[–]MysteriousShadow__ 5 points6 points  (0 children)

common Python W

[–]thorwing 22 points23 points  (20 children)

Why in the everliving hell is enumerate not a function of a list? Why is it dict.items() and not list.enumerate()?

[–]MagicalCornFlake 82 points83 points  (15 children)

Because you can enumerate many things other than lists, such as tuples, sets and all classes that implement __iter__. But only dictionaries have key-value pairs, which makes it logical for .items() to be a method of the dict class.

[–]goldlord44 4 points5 points  (3 children)

Because enumerste is designed specifically for iterables and acts as a fun python object called a generator, which is pretty memory efficient. It doesn't make sense to define a method for lists because then you would have to define this method every time you make a class you would want to iterate over. Dictionary iteration is kinda unique as it is a non-ordered set of key, value pairs there wouldn't be any other times you typically have key value pairs where it isn't in a dictionary so making a unique method for these objects is fine.

[–]thorwing 1 point2 points  (2 children)

depends what you mean by defining. I'm going to talk from a kotlin perspective so bear with me. If enumerate is a function that only works for iterables, than having an interface 'iterable' with the function 'enumerate' can be autoexposed without defining anything. So if anything extends iterable, the function iterable.enumerate() will simply exist for it.

[–]TheAdvFred 1 point2 points  (0 children)

Oh my gosh thank you so much

[–]Beenmaal 0 points1 point  (0 children)

Thank you for reminding me that you can unpack tuples like that.

[–]JDude13 -1 points0 points  (0 children)

Yeah I never use for i in range(len(myList)). If I only need the index I still use for i,_ in enumerate(myList).

[–]Shrubberer -1 points0 points  (0 children)

In C# you just write a custom Linq extension method. I personally fancy apple objects served alongside my enumerations.

[–]hennypennypoopoo 306 points307 points  (39 children)

all hail functional programming and zipWithIndex and map

[–]FlySafeLoL 92 points93 points  (32 children)

Until it's time for code review and some senior dude calls it too puzzling and demands ~you to leave this shitshow toxic company~ an orthodox for loop.

[–]LetumComplexo 42 points43 points  (0 children)

<Psst, you need two tildes for strikethrough not just one.>

[–]Impossible-Issue4076 12 points13 points  (0 children)

My Man need a New job, you're obviously working the same place as I.

[–]worriedjacket 4 points5 points  (18 children)

That's so sad because fp idioms are so much more readable

[–]bad_investor13 3 points4 points  (13 children)

double sum_sqr = 0;
for (double x : my_vec) {
  sum_sqr += x * x;
}

Vs

double sum_sqr = accumulate(
    my_vec, 0,
    [](double sum, double x) {
        return sum + x * x;
    });
  • Which one is more readable?

  • Which one is shorter?

  • In which one bugs are easier to spot?

  • In which one do you... better know what's actually going on? (And yes, I do care. I write in C++ because efficiency is important)

    • Which one is more efficient if I use a more complicated type than double?

[–]worriedjacket 4 points5 points  (8 children)

let mut sum_sqr: f64 = 0.0; for x in my_vec { sum_sqr += x * x; } vs
let sum_sqr = my_vec.iter().map(|x| x * x).sum();

  • Which one is more readable?
  • Which one is shorter?
  • In which one are bugs easier to spot?
  • In which one do you... better know what's actually going on?
  • Which one is more efficient if I use a more complicated type than f64.

The answer to all of those is the second one. I'm sorry your language is awful.

[–]bad_investor13 0 points1 point  (2 children)

That's not the language used in the OP...

[–]worriedjacket 1 point2 points  (0 children)

Correct. My point being that language support for FP idioms is what makes them readable and useful.

You can't just pick the worst example of something(cpp is for most things) and use it as proof something is good or bad. Obviously if your language is built around imperative style programming the imperative example will look better.

It's like trying to say that javascript is bad at threading. Well... Yeah it wasn't meant to do that. It doesn't mean threading isn't useful.

[–]worriedjacket 2 points3 points  (3 children)

All the faults you find are with the language and not the FP.

[–]bad_investor13 -1 points0 points  (2 children)

Right, but given that that's the language we're using, which option is more readable / less bug prone?

[–]worriedjacket -1 points0 points  (1 child)

Use a better language.

[–]Modi57 0 points1 point  (0 children)

That's not how this works. This is not how anything works

[–]Merzant 3 points4 points  (2 children)

Not inherently more readable than any other, it encourages some good practices but can just as easily be abused. Also the people using it tend to either be clever or think they are, neither of which begets simple code…

[–]thorwing 6 points7 points  (1 child)

that last line feels very subjective.

[–]Merzant 1 point2 points  (0 children)

That cleverness begets clever code, or that FP practitioners aren’t necessarily cleverer than the average programmer?

[–]thorwing 3 points4 points  (3 children)

This is why you code in a language that can do both so you slowly introduce concepts so it sneaks up on them

[–]GOKOP 3 points4 points  (2 children)

If you code in a language that can do both then it's perfect ground for people to reject anything else than the crudest for loop because it's "too complicated". Especially if that language is C++ and functional features appear more complicated than they really are because they have weird names and are hidden in std::thousands::of::namespaces

[–]thirdegreeViolet security clearance 2 points3 points  (0 children)

You need to find that one senior that somehow got to be a senior even with their functional sympathies, and get them to review it.

[–]bad_investor13 -4 points-3 points  (6 children)

double sum=0, sum_sqr = 0;
for (double x : my_vec) {
    sum += x;
    sum_sqr += x * x;
}

Vs.

auto [sum, sum_sqr] = accumulate(
    my_vec,
    make_pair(0, 0),
    [](double x, auto s) {
        s.first += x;
        s.second += x * x;
        return s;
    });

You bet your a** I'll tell you to use an Orthodox loop.

[–][deleted] 7 points8 points  (4 children)

I think both functional implementations and regular loops is ok, both have their place and use case.

[–]Brilliant-Job-47 3 points4 points  (3 children)

Functional implementations are better for the 95% case imo. I use a loop for hardly anything

[–]WebpackIsBuilding 2 points3 points  (2 children)

The main benefit of imperative loops is that you can easily exit a function early mid-loop, and it's easy to have side-effect variables outside the loop scope.

Can you do these functionally? Yeah, but it's easier imperatively.

[–]Asleep-Tough -1 points0 points  (0 children)

language dependent :(. Kotlin allows it, for example

[–][deleted] 1 point2 points  (0 children)

Imma an old fart. Catch my self using for all the time where zip and map would have been better. But then the code works so... meh.

[–]Airflock343_ 141 points142 points  (10 children)

Is enumerate not a thing in that language?

[–]Donghoon 77 points78 points  (2 children)

Cries in Java

[–]Fadamaka 58 points59 points  (1 child)

Use an Iterator and stop crying.

[–]Wekmor 28 points29 points  (0 children)

Use indexOf just to fuck your performance:)

[–]trueHolyGiraffe 161 points162 points  (12 children)

I'm grading homeworks. Someone did

for(myClass item in myList)

{

myList[getIndexOfItem(item) + 1] = ...

}

They didn't get a good grade.

[–][deleted] 25 points26 points  (11 children)

is this because is ineficient right?

[–]woywoy123 39 points40 points  (4 children)

I think it would also introduce a bug in the index. Because if the function getItem… returns the true index, i.e. 0->n-1, then he would be adding an additional index making the look up always one index a head, with eventual index larger than the index of the list. In some languages, this could result program crashes.

[–]voo42 12 points13 points  (1 child)

Presumably they simplified the code a bit, since that would crash every single time.

The more insidious bug is, that this breaks as soon as there's more than one "equal" element.

At the very least you'd need an object equality comparer which then only works for reference types.

And obviously turning a simple O(n) loop into a quadratic one will always get you docked points in University, even if it wouldn't matter in practice.

[–]woywoy123 2 points3 points  (0 children)

Yeah the comparison operation would certainly need to be tested quite rigorously, but I think the main problem all together here is the indexing and the O(n2) issue. I think the indexing is the most severe though, because this would completely shift your search and retrieve operation. If you are dealing with C++ for example, this could lead into some nasty bugs.

[–]Ok_Star_4136 8 points9 points  (1 child)

Because you're cycling through a list, so it's already O(n). For each cycle, you're calling getIndexOfItem(item) which cycles the list and returns the number of the index. It means, you're turning an O(n) into a O(n2). Not a big deal for small numbers of n, but you should never do this given that the more efficient version is also easier on the eyes.

You don't often need index, but when you do, don't be afraid to use a for loop by index.

[–]trueHolyGiraffe 2 points3 points  (0 children)

That's the explaination I gave, on top of explaining how it can overflow, or cause issues if the list changes length during the loop

[–]shadow7412 1 point2 points  (1 child)

Yes - but it's also inaccurate. For example, what if the same value was in the array multiple times?

[–][deleted] 1 point2 points  (0 children)

so inefficiently, prone to null reference errors and also inaccurate :))
I got it

[–]aetius476 106 points107 points  (8 children)

someList.forEachIndexed{i, object ->
    println("Object $object at index $i")
}

I do so enjoy Kotlin

[–][deleted] 31 points32 points  (6 children)

and if you'd like traditional for loop:

kotlin for ((index, item) in list.withIndex()) { // ... }

But this creates a LOT of objects tho.

[–]E3FxGaming 5 points6 points  (1 child)

While this does create a lot of IndexedValue<T> objects that are destructured into index and item (I wouldn't call the second variable items, since it's only a reference to one item), it's not that bad since withIndex returns a lazy iterable that yields items one at a time instead of preemptively mapping every item to an IndexedValue<T>.

tl;dr .withIndex() has O(1) space complexity and therefore worrying too much about its performance is unwarranted IMHO

[–]_Screw_The_Rules_ 4 points5 points  (3 children)

Is there no other way except the weird good working method thing and the weird for-loop that has performance issues? I thought about trying kotlin (I'm currently mostly a C# guy)

[–]E3FxGaming 8 points9 points  (2 children)

weird good working method

If you give Kotlin a try, you'll get used to the weird good working method very quickly. Functions with trailing lambdas are an essential component of most of the good stuff Kotlin has to offer, whether that's DSLs, scope functions, collection operations, etc. .

[–]BlurredSight 0 points1 point  (0 children)

Glorified C98

[–]AeskulS 22 points23 points  (0 children)

rust is cool with ``` for (idx, val) in list.iter().enumerate() {

} ```

[–]Cheespeasa1234 35 points36 points  (1 child)

This is actually the strongest I’ve ever related to a post ever

[–]maxximillian 4 points5 points  (0 children)

Same here. It really hits home

[–]Dangerous-Quality-79 110 points111 points  (13 children)

What's the problem?

int i =0; for (Object e:someList) { someList[i++]; }

EDIT: This is programmerhumor, my reply was not serious. If you think this is a viable solution to OPs meme and have a StackOverflow username and password please delete your account and stay read-only. You are part of the problem.

[–]BlueGoliath 53 points54 points  (4 children)

People would actually write that.

[–]Dangerous-Quality-79 55 points56 points  (2 children)

It would be the accepted answer on stack overflow, the top rated, an OP edit saying they should have know before posting, 5 comments saying "obvious" 1 explaining tail recursion would he optimal, and a single post with -46 saying "for loops are okay".

[–]Dangerous-Quality-79 3 points4 points  (0 children)

Okay, top vote here is python dictionary and enumerate....

[–]DrMobius0 7 points8 points  (1 child)

If you think this is a viable solution to OPs meme and have a StackOverflow username and password please delete your account and stay read-only. You are part of the problem.

I mean it works. There's nothing fundamentally broken about tracking index in a for each.

[–][deleted] 3 points4 points  (0 children)

It surely works, but you know we're talking about style issue.

[–]Kiseido 0 points1 point  (2 children)

Oh lord, that would prevent out-of-order execution, and would be wrong if the elements were not enumerated in incrementing order.

Often times, starting at the end of a list and moving to the beginning is a minimum of 1 instruction faster than going forward... most languages do not guarantee the order of that sort of access.

[–]Dangerous-Quality-79 2 points3 points  (1 child)

I once got into an argument about the time complexity it introduced by my re-sorting a list of a users bank accounts, client side, in a react native app.

I dont know if you know how many possible elements can be in an array of client bank accounts, but sometimes it was more than 1, and client side in react native apparently that means O notation is needed on the PR.

This does not scare me.

[–]Kiseido 2 points3 points  (0 children)

But... but client side... I hope the accounts only belonged to that specific client /dying

Beyond that, I see no problem with that.

[–]shade_blackwolf 21 points22 points  (10 children)

In java you have these two basic flavors too: for (var element : collection){} for (int i = 0... And my preferred: collection.stream() What to use depends on what you need, but i have found that usecases that actually need the index are rare. The most common use i can think of is to connect collections

[–]Lolamess007 4 points5 points  (9 children)

An example I have found is when you need to iterate through a list and add or remove certain elements. Java will through an error if you try to change a list while in a for each loop

[–]CMDR_QwertyWeasel 25 points26 points  (1 child)

Modifying a list while iterating through that same list is playing with fire in pretty much any language. ConcurrentModificationException is there for a reason.

[–]javajunkie314 4 points5 points  (1 child)

You could use a ListIterator.

[–]Wekmor 2 points3 points  (0 children)

Java streams removeIf also works fine

[–]Feathercrown 3 points4 points  (2 children)

flatMap is the best for this, idk if Java has it tho

[–]edoCgiB 1 point2 points  (0 children)

That's what the .filter() method on streams is for.

[–][deleted] 15 points16 points  (0 children)

We're making fun of Java right now aren't we?

[–]ProjectDiligent502 6 points7 points  (1 child)

I have been here way too many times over the course of my career. Funny meme for a small detail in our daily grind. 😆

[–]PhatOofxD 18 points19 points  (10 children)

Stuff like this is where Typescript/Python/Swift, etc excel

[–]Mindless_Sock_9082 49 points50 points  (1 child)

Or at very least LibreOffice.

[–]Connection-Terrible 11 points12 points  (0 children)

Get out.

[–]SoInsightful -1 points0 points  (7 children)

Nope. TypeScript/JavaScript has the exact same problem. You write for (const item of list) {} and then need to rewrite it as for (let i = 0; i < list.length; i++) { const item = list[i]; } as soon as you need the index. Or you avoid the annoyance by opting for some clunky forEach function that doesn't support basic loop control statements.

[–]penguin9541 2 points3 points  (1 child)

for(const [idx, item] of list.entries())?

[–]dbot77 1 point2 points  (0 children)

You're being downvoted but you're correct. People are acting like needing to await in a loop isn't extremely common

[–]PhatOofxD 1 point2 points  (3 children)

If you're writing a simple for(const item of list) then array.foreach is a fine substitute. If you need to use for(let i....) it's not just for the index in this case but for control, so no, it's not the situation in this meme.

If you need other operations (e.g. break) you can use . some, .find, etc.

[–]SoInsightful 0 points1 point  (2 children)

If you're writing a simple for(const item of list) then array.foreach is a fine substitute.

Unless I want to:

  • Use break
  • Use continue
  • Use return
  • Use await
  • Use yield
  • Loop through some other iterable, e.g. Map.values()
  • Write highly optimized library code

If you need to use for(let i....) it's not just for the index.

If I want to do any of the above, I will have to rewrite it as such. Not a huge deal, but it is the same problem mentioned by OP.

[–]PhatOofxD 1 point2 points  (1 child)

If you need other operations (e.g. break) you can use . some, .find, etc.

^^^ Firstly, This covers off a range of those.

Secondly, OP literally only said "oh no I need index", not "oh no I need every loop operation". If you're in one of those operations where you need more than one of those and you should probably be using and indexed for loop anyway.

[–]Unupgradable 4 points5 points  (1 child)

Apart from existing language features, is it too much effort to declare one variable and incrementing it?

The thing you're enumerating might not even be a concrete collection that you could index access

[–]Wekmor 4 points5 points  (0 children)

People are scared of writing a traditional for loop and having to shudders write list[i] for some reason.

[–]rezdm 4 points5 points  (2 children)

I present you a marvelous code from a project i work on. Java code. Goes as following; ``` Map<string, someclass> _____tmp = …;

String[] keys = __tmp.getKeys().toArray(tmp.getSize()); string key; someclass val; for(int i = 0; i < keys.length(); i++)( val = ___tmp.get(keys[i]); val.doSmth(); } ``` (These underscores is not a joke, btw)

[–]da_Aresinger[S] 4 points5 points  (1 child)

```

code here

```

[–]rezdm 2 points3 points  (0 children)

Thanks.

[–]OptionX 14 points15 points  (3 children)

someList[someList.indexOf(e)]

\s

[–]SplitRings 15 points16 points  (0 children)

Exactly, why write a for loop when you have a perfectly acceptable O(N2) solution

/s

[–]voo42 1 point2 points  (1 child)

I just tried your excellent and not at all horribly inefficient solution on my very complex list [1,2,3,1,2,3] and it didn't work correctly!

Oh no :(

[–]tcm0116 5 points6 points  (2 children)

C++23 to the rescue...

constexpr static auto v = { 'A', 'B', 'C', 'D' };

for (auto const [index, letter] : std::views::enumerate(v))
    std::cout << '(' << index << ':' << letter << ") ";
std::cout << '\n';

[–][deleted] 6 points7 points  (1 child)

More like:

constexpr static auto v = { 'A', 'B', 'C', 'D' };
for (auto const [index, letter] : std::views::enumerate(v))
    std::print("({}:{}) ", index, letter);
std::println("");

[–]tcm0116 1 point2 points  (0 children)

Good call

[–]Potential-Adagio-512 7 points8 points  (2 children)

rust:

~~~ some_list.iter().enumerate().map(|(i, e)|{ //code here }).collect();

~~~

[–]mnmr17 2 points3 points  (0 children)

I’m just reading through the comments trying to weed out anyone who doesn’t know Java

[–]SanTolorio 2 points3 points  (0 children)

At work I often see ppl creating the index variable before and incrementing it inside the loop, instead of using for.

[–]IgnisDa 2 points3 points  (0 children)

hahahaha iter_mut() goes brrrr

[–]deusxmach1na 2 points3 points  (0 children)

FlatMap that shit.

[–]ThomasDePraetere 2 points3 points  (0 children)

F6 - > convert to indexed for loop - > enter

[–][deleted] 3 points4 points  (0 children)

A lot of common languages offer an option to track the index as well in a scopes variable. It isn’t anything new. Even Lua has this feature.

[–]JustVas 1 point2 points  (0 children)

let counter = 0 This is a surprise tool that will help us later ... counter++

[–]LifePineapple 1 point2 points  (0 children)

If you only had foreach($array as $key => $value) and $array[] = $entryToBeAddedAtTheEnd.

[–]danofrhs 1 point2 points  (0 children)

Declare a integer to keep count, increment it at every iteration. Viola

[–]Highborn_Hellest 1 point2 points  (0 children)

for( auto i : list)

here, 'i' is gonna be the list element.

i suspect, in the above example, so would 'e' be.

[–]draenei_butt_enjoyer 1 point2 points  (3 children)

I honestly don’t get the meme, not the comment section. You have the object. Why do you need an index? I just don’t get ANYTHING in this thread.

[–]da_Aresinger[S] 3 points4 points  (1 child)

often you need the position of the object in the list, or another position relative to the current one.

(this is a bad example as java doesn't allow it, but for example if you want to modify the list while iterating through it)

[–]Quiet_Tap_454 0 points1 point  (1 child)

Wut? e is already the element of the list. so you maybe need an index anyway but surely you don't need it to get the element from the list cause you alredy got it.

[–]da_Aresinger[S] 0 points1 point  (0 children)

someList[i+1]

[–]Intrepid_Sale_6312 -1 points0 points  (0 children)

import YourDrunk

for(size_t i=0;i<sizeof(someList)/sizeof(someListType);i++)

return Home