List subscript C++

Photo by Igor Miske on Unsplash

I was preparing to demonstrate indexing and slicing lists to a group of fellow Python beginners a few days ago, and I got stuck on what seemed like a couple of pretty basic use cases. So after poking around a bit to get un-stuck, I figured it was worth sharing what I learned.

Accessing the items in a list [and in other iterables like tuples and strings] is a fundamental skill for Python coders, and many Python tools follow similar conventions for indexing and slicing [e.g. numpy Arraysand pandas DataFrames]. So it’s worth being familiar with the ins and outs.

Definitions and Stage-Setting

“Indexing” means referring to an element of an iterable by its position within the iterable. “Slicing” means getting a subset of elements from an iterable based on their indices.

By way of analogy, I was recently summoned to jury duty, and they assigned each potential juror a number. You might say my juror number was my index. When they said, “Juror number 42; please stand,” I knew they were talking to me. When they said, “Jurors 37 through 48, please report back at 3:30 pm,” that slice of the larger group collectively sighed and went to lunch.

Let’s first create a list we can play around with using a list comprehension:

Indexing

To retrieve an element of the list, we use the index operator [[]]:

Lists are “zero indexed”, so [0] returns the zero-th [i.e. the left-most] item in the list, and [1] returns the one-th item [i.e. one item to the right of the zero-th item]. Since there are 9 elements in our list [[0] through [8]], attempting to access my_list[9] throws an IndexError: list index out of range, since it is actually trying to get the tenth element, and there isn’t one.

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don’t have to programmatically find out the length of the iterable in order to work with elements at the end of it. The indices and reverse indices of my_list are as follows:

Slicing

A slice is a subset of list elements. In the case of lists, a single slice will always be of contiguous elements. Slice notation takes the form

where start is the index of the first element to include, and stop is the index of the item to stop at without including it in the slice. So my_list[1:5] returns ['b', 'c', 'd', 'e']:

Leaving either slice boundary blank means start from [or go to] the end of the list. For example:

Using a negative indexer will set the start/stop bounds relative to their position from the end of the list, so my_list[-5:-2] returns ['e', 'f', 'g']:

Note that if you try my_list[-2:-5], you’ll get an empty list. This was something I got tripped up on, but here’s what’s happening: in order to be included in the slice, an element must be at or to the right of the start boundary AND to the left of the stop boundary. Because the -2 is already to the right of -5, the slicer stops before populating any value into the slice.

A for loop works exactly the same way; the first loop below has no output, but the second does:

Stepping

The slicer can take an optional third argument, which sets the interval at which elements are included in the slice. So my_list[::2] returns ['a', 'c', 'e', 'g', 'i']:

And my_list[1::2] returns ['b', 'd', 'f', 'h']:

Negative step values reverse the direction in which the slicer iterates through the original list:

The indexed positions of list elements don’t change, but the order in which the elements are returned does. The sense of the start and stop boundaries is also reversed, so the start value should be the right-most position in the slice, and the stop value should be to the left of that. So my_list[5:3:-1] gives us [‘f’, ‘e’]:

Likewise, my_list[-2:-5:-1] gives us ['h', 'g', 'f']:

And my_list[-1:-8:-3] gives us ['i', 'f', 'c']:

I hope this saves you some of the confusion I encountered while working through indexing and slicing, especially with negative steps.

lst = {Subscript[1, 3], Subscript[2, 2], Subscript[4, 1]};

$\left\{1_3,2_2,4_1\right\}$

ClearAll[foo, editFX]; foo = Flatten[GatherBy[Join[#1, Subscript @@@ Tally[#2] ], First] /. {Subscript[x_, a_], Subscript[x_, b_]} :> [Subscript[x, a + #3 b] /. Subscript[_, 0] :> Sequence[]]] &; editFX[lst_, arg1 : {___}, arg2 : {___}] := With[{t = foo[lst, arg1, -1]}, foo[t, arg2, 1]]; editFX[lst, {1, 1, 4}, {2, 5}]

$\left\{1_1,2_3,5_1\right\}$

Or

ClearAll[editFX2]; editFX2 = Fold[foo[#1, First@#2, Last@#2] &, #, {{#2, -1}, {#3, 1}}] &; editFX2[lst, {1, 1, 4}, {2, 5}]

$\left\{1_1,2_3,5_1\right\}$

IndexOf[T, Int32]

Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the List that extends from the specified index to the last element.

IndexOf[T, Int32, Int32]

Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the List that starts at the specified index and contains the specified number of elements.

IndexOf[T]

Searches for the specified object and returns the zero-based index of the first occurrence within the entire List.

The following example demonstrates all three overloads of the IndexOf method. A List of strings is created, with one entry that appears twice, at index location 0 and index location 5. The IndexOf[T] method overload searches the list from the beginning, and finds the first occurrence of the string. The IndexOf[T, Int32] method overload is used to search the list beginning with index location 3 and continuing to the end of the list, and finds the second occurrence of the string. Finally, the IndexOf[T, Int32, Int32] method overload is used to search a range of two entries, beginning at index location two; it returns -1 because there are no instances of the search string in that range.

using namespace System; using namespace System::Collections::Generic; void main[] { List^ dinosaurs = gcnew List[]; dinosaurs->Add["Tyrannosaurus"]; dinosaurs->Add["Amargasaurus"]; dinosaurs->Add["Mamenchisaurus"]; dinosaurs->Add["Brachiosaurus"]; dinosaurs->Add["Deinonychus"]; dinosaurs->Add["Tyrannosaurus"]; dinosaurs->Add["Compsognathus"]; Console::WriteLine[]; for each[String^ dinosaur in dinosaurs ] { Console::WriteLine[dinosaur]; } Console::WriteLine["\nIndexOf[\"Tyrannosaurus\"]: {0}", dinosaurs->IndexOf["Tyrannosaurus"]]; Console::WriteLine["\nIndexOf[\"Tyrannosaurus\", 3]: {0}", dinosaurs->IndexOf["Tyrannosaurus", 3]]; Console::WriteLine["\nIndexOf[\"Tyrannosaurus\", 2, 2]: {0}", dinosaurs->IndexOf["Tyrannosaurus", 2, 2]]; } /* This code example produces the following output: Tyrannosaurus Amargasaurus Mamenchisaurus Brachiosaurus Deinonychus Tyrannosaurus Compsognathus IndexOf["Tyrannosaurus"]: 0 IndexOf["Tyrannosaurus", 3]: 5 IndexOf["Tyrannosaurus", 2, 2]: -1 */ using System; using System.Collections.Generic; public class Example { public static void Main[] { List dinosaurs = new List[]; dinosaurs.Add["Tyrannosaurus"]; dinosaurs.Add["Amargasaurus"]; dinosaurs.Add["Mamenchisaurus"]; dinosaurs.Add["Brachiosaurus"]; dinosaurs.Add["Deinonychus"]; dinosaurs.Add["Tyrannosaurus"]; dinosaurs.Add["Compsognathus"]; Console.WriteLine[]; foreach[string dinosaur in dinosaurs] { Console.WriteLine[dinosaur]; } Console.WriteLine["\nIndexOf[\"Tyrannosaurus\"]: {0}", dinosaurs.IndexOf["Tyrannosaurus"]]; Console.WriteLine["\nIndexOf[\"Tyrannosaurus\", 3]: {0}", dinosaurs.IndexOf["Tyrannosaurus", 3]]; Console.WriteLine["\nIndexOf[\"Tyrannosaurus\", 2, 2]: {0}", dinosaurs.IndexOf["Tyrannosaurus", 2, 2]]; } } /* This code example produces the following output: Tyrannosaurus Amargasaurus Mamenchisaurus Brachiosaurus Deinonychus Tyrannosaurus Compsognathus IndexOf["Tyrannosaurus"]: 0 IndexOf["Tyrannosaurus", 3]: 5 IndexOf["Tyrannosaurus", 2, 2]: -1 */ Imports System.Collections.Generic Public Class Example Public Shared Sub Main[] Dim dinosaurs As New List[Of String] dinosaurs.Add["Tyrannosaurus"] dinosaurs.Add["Amargasaurus"] dinosaurs.Add["Mamenchisaurus"] dinosaurs.Add["Brachiosaurus"] dinosaurs.Add["Deinonychus"] dinosaurs.Add["Tyrannosaurus"] dinosaurs.Add["Compsognathus"] Console.WriteLine[] For Each dinosaur As String In dinosaurs Console.WriteLine[dinosaur] Next Console.WriteLine[vbLf & _ "IndexOf[""Tyrannosaurus""]: {0}", _ dinosaurs.IndexOf["Tyrannosaurus"]] Console.WriteLine[vbLf & _ "IndexOf[""Tyrannosaurus"", 3]: {0}", _ dinosaurs.IndexOf["Tyrannosaurus", 3]] Console.WriteLine[vbLf & _ "IndexOf[""Tyrannosaurus"", 2, 2]: {0}", _ dinosaurs.IndexOf["Tyrannosaurus", 2, 2]] End Sub End Class ' This code example produces the following output: ' 'Tyrannosaurus 'Amargasaurus 'Mamenchisaurus 'Brachiosaurus 'Deinonychus 'Tyrannosaurus 'Compsognathus ' 'IndexOf["Tyrannosaurus"]: 0 ' 'IndexOf["Tyrannosaurus", 3]: 5 ' 'IndexOf["Tyrannosaurus", 2, 2]: -1

IndexOf[T, Int32]

IndexOf[T, Int32, Int32]

IndexOf[T]

Video liên quan

Chủ Đề