The PowerShell Array Removal

  • Comments posted to this topic are about the item The PowerShell Array Removal

  • 9 is the correct answer (shame on me), but there is a subtlety here with PowerShell arrays. Setting $numbers[4] = $null does not change the size of the array, only the value stored at index 4. $numbers.length and $numbers.count still return 10. A simple loop over the elements also shows that it's still there.

    foreach ($elem in $numbers) { Write-Host $elem }
    1
    2
    3
    4

    6
    7
    8
    9
    10

     

  • I don't get it. If you set element 4 to Null, why is it that number 5 vanishes from the array?

  • PowerShell arrays are 0-based. We have 10 elements, so the index goes from 0 to 9. The assignment was $numbers = @(1,2,3,4,5,6,7,8,9,10). So $numbers[0] = 1, $numbers[1] = 2, ..., $numbers[4] = 5, ..., $numbers[9] = 10.

  • It was a weird thing I stumbled on when working with arrays and removing elements as dale_berta noted, the array is still the same size, which is expected. It shouldn't actually remove the item from memory, but change the value. What's weird is that the display doesn't show it, which I think would be confusing to many users.

    If I were to set an array element in python to None, it's still there if I just pick the array. In C, the memory location is still there and I either copy the array or move elements to fill a hole, depending on what I want to do.

    I think this is a poor implementation choice in PoSh.

  • dale_berta wrote:

    PowerShell arrays are 0-based. We have 10 elements, so the index goes from 0 to 9. The assignment was $numbers = @(1,2,3,4,5,6,7,8,9,10). So $numbers[0] = 1, $numbers[1] = 2, ..., $numbers[4] = 5, ..., $numbers[9] = 10.

    DOH! All the years I've been programming and that didn't occur to me. SMH - thanks.

  • This was removed by the editor as SPAM

  • saying an array is '0' based does not really illustrate the situation.  The index is a position offset. So the first element is at the allocated address and the second element is offset by 1 position and the third by 2 positions etc.

    At the end of most articles is a small blurb called a person's signature which exists to provide information about how to get in touch with the person posting, including their email address, phone number, address, or where they're located. Signatures have become the graffiti of computers. People put song lyrics, pictures, philosophical quotes, even advertisements in them. (Note, however, that advertising in your signature will more often than provoke negative responses until you take it out.)

Viewing 8 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic. Login to reply