r/PowerShell • • Sep 17 '20

PowerShell vs Python Reference

https://blog.ironmansoftware.com/powershell-vs-python/
206 Upvotes

51 comments sorted by

View all comments

Show parent comments

0

u/setmehigh Sep 17 '20

Maybe I'm dumb, but why would you want to do this? I can't think of a reason, but I haven't run into a situation where I needed it either...

4

u/DecentWalrus Sep 17 '20

An example for slicing would be if you only wanted to grab the first three values of a list. For example, I have a list of names of people who ran a race. The list is already ordered by who finished first to who finished last. If I want to print the top three finishers, I'd do this:

Code:

finishers = ["Tom", "Sally", "Taylor", "Jack", "Ginger", "John"]
print(f'The top three finishers are: {finishers[0:3]}')

Result:
The top three finishers are: ['Tom', 'Sally', 'Taylor']

Now you could go the extra step of actually formatting that properly and such but it's just a simple way to grab a slice of the list.

As for using the step option, it allows for quick access to, for example, all odd or even positioned values in the list. The simplest example is the one given in the original comment where you may need to count by 2s.

2

u/omers Sep 17 '20 edited Sep 17 '20

finishers[0:3]

That's reproducible in PS with .. or a list of indicies.

C:\> $finishers = @("Tom", "Sally", "Taylor", "Jack", "Ginger", "John")
C:\> $finishers[0..2]
Tom
Sally
Taylor
C:\> $finishers[0,1,2]
Tom
Sally
Taylor

Every n-th I do not believe is possible without using /u/bozho's method or a loop... You can "compress" (remove the pipeline) bozho's method to this: $finishers.Where({$finishers.IndexOf($_) % 2 -eq 0}) but it's still not clean like in some other languages.

In a script where keeping it to one line isn't an issue I'd probably do something like this:

$Finishers = @("Tom", "Sally", "Taylor", "Jack", "Ginger", "John")
$OddIndicies = @(0..$Finishers.GetUpperBound(0)) | ? {$_ % 2 -eq 0}
$Finishers[$OddIndicies]

1

u/blooping_blooper Sep 18 '20

for that specific case couldn't you also do

$Finishers | select -first 3