text:
Determine if an Array contains something other than 2
Take an array which consists of positive integers or arrays, output if it only contains 2s.
Output should be a truthy or falsey value (Sorry if this destroys answers)
Truthy Test Cases
[2]
[2,2]
[[2],[2,2],2]
[]
[[],[]]

Falsey Test Cases
[1]
[22]
[2,2,2,1]
[[1,2],2]

Standard Loopholes Are forbidden.
Default IO rules apply.
Code-golf, Fewest bytes wins!

Can we take in a string representing the array?

Will there be objects other than numbers and other arrays in the arrays

There will only be arrays and numbers, and a string representing the array is fine.

Is it okay if we output 0  for truthy testcases, and some positive integer for falsey ones?

Can we assume input numbers are positive?

Input numbers will not be non-negative, and any unique output pair is acceptable...

@ATaco Does "unique output pair" mean that "a positive integer for falsey" is not allowed?

I'll allow it, as it's still clearly distinguishable from a truthy result.

@ATaco so what exactly do you allow, and why would a cat program be invalid?

Is it OK to return true` in one case and raise an error in the other? I assume no, but I can shave a byte off if the answer's yes.

Atleast one output should be uniquely consistent. And yes, error is fine.

You should clarify exactly what outputs are expected. Default IO would imply Truthy-falsy, but the comments say that at least one output should be consistent. https://codegolf.meta.stackexchange.com/q/12305/31716

Alright, I'm going to be specific in the challenge, as this comment section is getting too much.

What kind of numbers? Compex int, compex float, float int, int , not negative?

What about:" Take an array void or contain integers or contain arrays of integers or array voids, output if it only contains 2s."

FTR and in the name of proper mathematical thinking: the array [[2]] does not contain a two.

Can the array contain floating point numbers like 2.2?

I know this challenge is almost 6 years old and there are a lot of comments, but I still don't see an answer to user58988's and user41805's comments: can the input contain floating point numbers like 2.2? Also, in one of the comments you mentioned "input numbers will not be non-negative" (aka input-numbers can be negative, 0, or positive). If this is correct, some of the answers (mostly the regex-based ones) currently fail for it and test cases with -2 would be appreciated.. (PS: Rules that have been clarified in comments should always be added to the challenge description.)

@KevinCruijssen Given the sheer number of answers that ignore the commented restriction (And the age of the challenge), I'd rather now state that answers needn't worry about numbers other than positive integers. I'll adjust the challenge description to specify this.

MATL, 3 bytes
2=p

Try it online!
Technically, this could just be
2=

Since an array containing any zero elements is falsy, but this seems cheap.

A list containing 0 is falsy? Oh man.

I don't think the 2-byte version is valid, since in the comments ATaco said that a unique output pair is valid.

I believe 2= fails for empty matrices, or?

@stewiegriffin That seems like a strange edge case to need to handle, but conveniently it does work: Try it online!

Yes, 2=p works fine. The shorter version in the end, 2=, doesn't. Also, "the strange edge cases" are two of the test cases. :-)

Python 2, 43 40 bytes
f=lambda l:l>=[]and all(map(f,l))or l==2

Try it online!

At time of posting this answer, it was still allowed per this meta consensus to output via throwing an error / not throwing an error. Therefore this answer at 26 bytes was valid:
f=lambda l:l==2or map(f,l)

Try it online!

That's a neat way to check whether an element is a list.

This is why I don't like that consensus.  It really ruins python golfing.

However since you are going by exit code you don't need the all, anything other than an error is truthy.

Prolog (SWI), 43 33 bytes
I smell... recursion.
Thanks to Emigna and Leaky Nun for saving 10 bytes!
Code
a([]).
a([X|T]):-(X=2;a(X)),a(T).

Try it online! or Verify all test cases!
Explanation:
For non-Prolog users, a list is formatted in the following way: [Head | Tail].
The Head is the first element of the list, and tail is the remaining list.  Test it here!. An important case here is that the tail of a list with 1 element is equal to []. You can test that here.
% State that an empty array is truthy.
a([]).

% If the list is not empty (covered by the previous line), we need to check
% whether the Head is equal to 2 or whether the head is truthy.
% After that, we only need to check if the remaining list is truthy.
a([Head | Tail]) :- (Head = 2; a(Head)), a(Tail).

Jelly, 4 bytes
F;2E

Try it online!
How it works
F;2E
F    flatten
 ;2  append 2
   E all elements are equal

Octave, 13 bytes
@(x)~any(x-2)

Verify all test cases.
This is an anonymous function taking one input argument, x. It subtracts 2 from all elements, checks if there are any non-zero elements. It negates the output to get true for cases where all values are zero.
This works because x-2 works for matrices of all sizes, including the empty matrix, [].
x-2 would be sufficient if there couldn't be empty matrices in the input.

Mathics, 28 bytes
Select[Flatten@#,#!=2&]=={}&

Try it online!

I think that the input {0} is allowed; that would result in a false positive.

JavaScript (ES6), 22 19 23 22 bytes
a=>!/[^2,]|22/.test(a)

Test it

f=
a=>!/[^2,]|22/.test(a)
console.log(" "+f([2])+": "+JSON.stringify([2]))
console.log(" "+f([2,2])+": "+JSON.stringify([2,2]))
console.log(" "+f([[2],[2,2],2])+": "+JSON.stringify([[2],[2,2],2]))
console.log(" "+f([])+": "+JSON.stringify([]))
console.log(" "+f([[],[]])+": "+JSON.stringify([[],[]]))
console.log(f([1])+": "+JSON.stringify([1]))
console.log(f([22])+": "+JSON.stringify([22]))
console.log(f([2,2,2,1])+": "+JSON.stringify([2,2,2,1]))
console.log(f([[1,2],2])+": "+JSON.stringify([[1,2],2]))

Nice one! I wonder if it could be shortened some more, but I doubt it.

Thanks, @Arnauld; still haven't figured out a way to improve on it.

Retina, 13 10 bytes
Thanks to Kritixi Lithos for saving 3 bytes.
\W|\b2

^$

Try it online!

Seems to fail for lists that contain -2.

05AB1E, 4 bytes
˜YQP

Try it online!
Explanation
˜      # flatten list
 YQ    # check each element for equality to 2
   P   # product of list

Why wouldn't 2 work instead of Y?

@EriktheOutgolfer: 2 works as well. I just like the fact that there are no numbers in it :)

APL (Dyalog), 5 bytes
∧/2=∊

Try it online!
Explanation
∧/                         Only
  2=                       2s are equal to
    ∊                      any of the elements in the enlisted form of the right argument

Mathematica, 15 bytes
FreeQ[x_/;x!=2]

It also works in Mathics. Try it online!

Haskell, 36 bytes
An anonymous function, takes a String and returns a Bool.
Use as (all((==2).fst).(reads=<<).scanr(:)[]) "[2,2,2,1]"
all((==2).fst).(reads=<<).scanr(:)[]

Try it online!
How it works

Haskell doesn't have builtin mixed-type lists, so we take a string as argument.
scanr(:)[] generates a list of all suffixes of the string.
(reads=<<) tries to parse a number at the beginning of each suffix, combining the successes into a list of tuples (n,restOfString).
all((==2).fst) checks if all the parsed numbers are 2.

How about just not.all(\elem`"2,[]")`?

@zbw That fails because of numbers like 22.

Python 2, 38 bytes
lambda l:l.strip('[],2')==l*('22'in l)

Try it online!
Takes in a string without spaces, outputs a bool.
Checks if removing all the characters '[],2' of l gives the empty string. Also checks that 22 is not a substring -- if it is, the input l is used in place of the empty string to compare to the result of removal, and that always fails.

Mathematica, 24 bytes
Cases[t=Flatten@#,2]==t&

Pure function returning True or False. After Flattening the nested array and calling it t, Cases[t,2] returns the list of elements that match the "pattern" 2, and ==t checks whether that's the whole list.
Mathematica, 29 bytes
(#//.{2->{},{{}..}->{}})=={}&

Not as short, but more fun. Starting from the input #, two replacement rules are applied until the result stops changing (//.): first, all 2s are replaced by {}s; and then any list whose entries are all empty sets ({{}..}) are replaced (repeatedly) by empty sets. If the rest is an empty set (=={}), we win.

Outgolfed, but I still really want to know what is being done here.

Ruby, 28 23 22 bytes - 5 bytes saved by G B
->x{x.flatten-[2]==[]}

Despite "flatten" being really long, it's still shorter than regex based solutions or recursive stuff that has to rescue errors in the base case. Ruby's built-in conflation of sets and arrays, however, is amazingly useful sometimes.

x.flatten.uniq==[2]

@NickM - that won't work on test cases like [] or [[],[]]. [2,*x].flatten.uniq==[2] is slightly longer

x.flatten|[2]==[2] would be shorter.

@GB and x.flatten-[2]==[] is shorter still. Thanks for the tip!

And yet regex wins: https://codegolf.stackexchange.com/a/120781/18535 :-)

JavaScript (ES6), 26 bytes
f=a=>a.map?a.every(f):a==2

Test cases

f=a=>a.map?a.every(f):a==2

console.log(f([2]))
console.log(f([2,2]))
console.log(f([[2],[2,2],2]))
console.log(f([]))
console.log(f([[],[]]))

console.log(f([1]))
console.log(f([22]))
console.log(f([2,2,2,1]))
console.log(f([[1,2],2]))

You need to count f= because you referred to it.

@LeakyNun Indeed. Fixed.

MATL, 4 bytes
2-a~

Try it online!
Breakdown:
           % Implicit input
2-         % Push 2 to the stack, and subtract from input
  a        % Any non-zero elements?
    ~      % Negate to get true for cases where all elements are zero.

Well, outgolfed. But I'm keeping this, since I'm quite happy I managed this all on my own (even though the task is super simple).

R, 28 bytes
function(x)!any(unlist(x)-2)

unlist(x) turns a (nested) list into a vector. Then 2 is subtracted from that vector. any converts (with a warning) numeric to logical and checks if there are any TRUEs. This is inverted with ! and output.
This works with nested lists because unlist by default works recursively to unlist all list entries of the initial list.
This also works with empty lists, because unlist(list()) becomes numeric(), an empty numerical vector. Coercion by any makes it logical(), which is interpreted as FALSE by any, and then reversed to TRUE by !.

pryr::f(!any(unlist(x)-2)) saves a couple of bytes.

this is the same length as all(unlist(x)==2) as well.

or you could also say any(unlist(x)-2) which returns a consistent TRUE if there is a non-2 value in the flattened array and a consistent FALSE if all the values are 2...

@Giuseppe Not sure if TRUE counts as falsey though :/

@BLT that's codegolf magic, imma check that out.

@JarkoDubbeldam it tends to get confused for more complex functions but for simple ones, it infers the arguments so you don't have to declare them (or write function). If only the package name were shorter...

@BLT, still very nice. Makes any answer using apply with an anonymous function that bit shorter.

@BLT maybe add it here: https://codegolf.stackexchange.com/questions/4024/tips-for-golfing-in-r?s=1|1.4077 ;)

@JarkoDubbeldam I did a few months ago: https://codegolf.stackexchange.com/a/111578/62105

well, there's still not a consensus on meta, but https://codegolf.meta.stackexchange.com/a/2192/67312

@Giuseppe I think this answer is pretty clear, and has a lot more upvotes than the other answers: https://codegolf.meta.stackexchange.com/a/2194/59530

JavaScript (ES6), 53 50 48 bytes
_=>(_+"").split`,`.map(c=>!c?2:c).every(c=>c==2)

Saved 5 bytes, thanks to @Shaggy!
Test Cases :

let f =

_=>(_+"").split`,`.map(c=>!c?2:c).every(c=>c==2)

console.log(f([2]))
console.log(f([2,2]))
console.log(f([[2],[2,2],2]))
console.log(f([]))
console.log(f([[],[]]))

console.log(f([1]))
console.log(f([22]))
console.log(f([2,2,2,1]))
console.log(f([[1,2],2]))

f([]) and f([[],[]]) should be truthy

@Arnauld Is it correct now?

I think so. :-)

Think you can save a couple of bytes with !c instead of c=="".

@Arnauld Thanks for pointing that out. This challenge was actually posted as a CMC in the Nineteenth byte. That CMC did not have anything to say regarding [[],[]] etc kind of test cases. When the challenge got posted on the main site, I quickly added my solution (It even asked me CAPTCHA!) without looking at rules! Thanks once again! :)

Save more with ("'+a) instead of a.join().

@Shaggy Won't that fail for [[][]] and similar cases?

Nope, it'll still return true properly.

One more: replace !c?2:c with c||2 or maybe even just c|2 - you'll need to double check that against the test cases .

Actually, you might even be able to use c^2 thus allowing you to replace c==2 with !c. Again, you'd need to run a full set of tests to double check it works.

Python 3, 55 bytes
No cheating. Uses nested list as input.
f=lambda a:all(type(x)!=int and f(x)for x in a if x!=2)

Try it online!

-1 byte: int!=type(x)and

Retina, 14 11 bytes
^(\W|2\b)+$

Try it online!

\W doesn't seem such a good criteria : 2.2 is a number that isn't 2, yet I suppose it would match

@Aaron I have just asked the OP on whether the array can containing decimal numbers. If they state that floating-point numbers will be present in the array, I will change my submission.

Yeah, I see RosLup asked the same question yesterday and hasn't got an answer yet. I hope OP will come soon to clarify !

05AB1E, 4 bytes
2‚˜Ë

Try it online!

Jelly, 4 bytes
F=2Ạ

Try it online!
Slightly different than Leaky's algorithm.
Explanation:
F=2Ạ
F    Flatten
 =2  Check if equal to 2 (vectorizes)
   Ạ Check if there isn't any falsey value

05AB1E, 7 bytes
˜DOsg·Q

Try it online! or Try All Tests!
˜D      # Flatten and duplicate
  O     # Sum one copy
   sg·  # Get double the length of the other copy
      Q # Check if they are equal

Java 8, 126 55 27 bytes
s->s.matches("(\\W|2\\b)+")

Port of @KritixiLithos's amazing Retina answer, excluding the ^...$, since String#matches always matches the entire String and adds the ^...$ implicitly.
-2 bytes thanks to @Jakob for reminding me of ^...$ isn't necessary for String#matches.
Try it here.

I hate to nullify all your work on the list solution, but couldn't you coerce to a string and use the string solution?

@Jakob You mean in the explanation? I am using a regex String solution at the moment. I've just kept my original List answer and it's explanation, because the String solution is a port. Are you asking to just remove the List solution? Or add an explanation for the String solution?

I mean that as long as you have a list solution you might as well shorten it by using the string solution in it. Like boolean c(java.util.List l){return(l+"").matches("^(\\W|2\\b)+$");} would work, right? Just wanted to point that out in case you were planning to further golf the list solution.

Oh and you can lose 2 bytes by removing ^ and $ in the regex, since String.matches only tests against the whole string.

@Jakob Removed the List answer entirely, converted to Java 8, and removed the ^...$. Forgot about that, even though I've used it quite a lot of times in the past..

Ruby, 21 bytes
->x{x*?!!~/[^2!]|22/}

Using a regex is actually shorter, because joining an array also flattens it.
How it works
->x{
    x*?!                -> Join array using an exclamation mark
        !~              -> String does not contain
          /[^2!]        -> characters different from '2' or '!'
                |       -> or
                 22/    -> '2' repeated at least twice
                    }

Try it online!

Curses! Nice work. What's this x*?!!~ construct?

Jelly, 3 bytes
2ṁ⁼

Try it online!
How it works
2ṁ⁼  Main link. Argument: A (array)

2ṁ   Mold 2 like A. This replaces each number in A by 2.
  ⁼  Test if the result is equal to A.

Thunno 2, 4 bytes
Ḟ2=p

Try it online!
Explanation
Ḟ2=p  # Implicit input
Ḟ     # Flatten the list
 2=   # Check for == 2
   p  # All are true?
      # Implicit output

Nekomata + -e, 3 bytes
2-ž

Attempt This Online!
2-      Minus 2
  ž     Check if all elements are zero

Wolfram Language (Mathematica), 13 10 bytes
2#2&

Try it online!
 is \[VectorLessEqual].

PHP<7.0, 29 Bytes
Input as as string array JSON encoded

<?=!ereg("22|[013-9]",$argn);

PHP<7.0, 42 Bytes
use the deprecated function ereg

<?=!ereg("22|[013-9]",json_encode($_GET));

PHP, 50 Bytes
prints 1 for true and nothing for false
-1 Byte for other wise remove !
or + 1 Byte for true 1, false 0  add + before !

<?=!preg_match('#22|[013-9]#',json_encode($_GET));

Try it online!

You don't need the $r variable: <?array_walk_recursive($_GET,function($i){$i-2&¨})?>1.

Python 2, 44 43 42 bytes
Takes x as the string representation of the list. This also assumes like in the example the representations have no spaces.
lambda x:set(x)<=set("[],2"*0**("22"in x))

Try it online!

Explanation
Both of these take the characters in the string representation of the input and determine if any characters other than [], 2 are in it.  They do this by casting to a set and comparing to the set of just those characters.  However this fails if we have a number other than 2 which has only digits of 2 (e.g. 22 or 222), in order to patch this case we multiply the string used to create the set by the negation of whether or not x contains "22".  If it contains it this will be the empty set, otherwise it will be the same as before.

lambda x:set(x)==set("[], 2")?

Fails for [22]

@LeakyNun Fixed

@LeakyNun Your suggestion fails for []

lambda x:set(x)<=set("[],2"*-~-("22"in x)) for -1

@ovs Already took that byte off a slightly different way, thanks though!

Pyth, 6 bytes
!-.nQ2

Very similar to my CJam answer. I'm still new to Pyth, so please tell me if there's anything I can golf off.
Explanation:
    Q   Input:     [[[], [2]], [1]]
  .n    Flatten:   [2, 1]
 -   2  Remove 2s: [1]
!       Not:       False

Japt -!, 6 5 4 bytes
c dÍ

Try it
c dÍ     :Implicit output of array
c        :Flatten
  d      :Any truthy (non-zero) when
   Í     :Subtracted from 2
         :Implicit output of negation of result

Ohm, 6 bytes
∙e]Å2N

Uses CP-437 encoding.
Explanation:
∙e]Å2E
∙e           ■Evaluate the input to form an array
   Å         ■any(              ,             )
  ]          ■    flatten(input)
    2N       ■                   lambda x:x!=2
             ■implict end of any and print

PHP, 46 bytes
<?=!preg_match('/:"(?!2")/',serialize($_GET));

@JörgHülsermann Could you please give an example? All the test cases seem to work. If you test it not through a browser, do you pass scalar values of $_GET as strings?

<?=!preg_match('/:"(?!2")/',$argn); and input is a string representation of the serialized array - 11 Bytes

Ruby 1.9+, 19 bytes
->x{x*$/!~/^2?+.$/}

Form is stolen from G B's answer. The main difference is that I join on a newline (the default value of $/), which lets me write a shorter regex by using the ^.$ special characters that have specific interactions with newlines.
The trick that makes this version-specific (1.9 and higher) is the use of the "possessive" quantifier 2?+. Like 2?, it'll match zero or one instances of a 2, but this form will hold onto that 2 forever and prevent it from being matched by the ., so a 2 on its own line won't match the overall regexp.

Kotlin, 90 bytes
Submission
fun r(i:String):Any{return i.replace(Regex("[\\[\\]2,]+"),"")==""&&!i.contains("22")}

TryItOnline
TryItOnline

Vyxal, 3 bytes
2J≈

Try it Online!
Append a 2, check if everything is equal

Raku, 13 bytes
*.flat.all==2

Try it online!

Clojure, 21 or 25 bytes
#(every?(set"[]2 ")%)
#(every? #{2}(flatten %))

The first one takes the argument as string, second one as an actual nested list.
#{2} is the set with one element 2, calling it with an existing element returns it and for a non-existing it returns nil (falsy).

CJam, 7 bytes
Input is in the form of a CJam array literal.
q~e_2-!

Explanation:
q  e# Read input: | "[[1 2] 2]"
~  e# Eval:       | [[1 2] 2]
e_ e# Flatten:    | [1 2 2]
2- e# Remove 2s:  | [1]
!  e# Not:        | 0

Actually, 10 bytes
⌠♂i⌡Y2#@-b

Try it online!
Explanation:
⌠♂i⌡Y2#@-b
⌠♂i⌡Y       call the function until the result stops changing (fixed-point combinator):
 ♂i           for each item: flatten
     2#@-   set difference: all items that are not 2s
         b  cast to boolean (1 if list is not empty, else 0)

Axiom, 280 bytes
w(x:Union(List(Any),NNI)):Boolean==(x case List(Any)=>(g:List(Any):=x;leaf? g=>return true;for i in g repeat(q:=w(i);q=false=>return false);return true);r:NNI:=x;r=2=>true;false)
m(b:List Any):Boolean==(for i in b repeat(q:=w(i::Union(List(Any),NNI));q=false=>return false);true)

ungolfed and test
f(x:Union(List(Any),NNI)):Boolean==
      x case List(Any)=>
              g:List(Any):=x
              leaf? g =>return true
              for i in g repeat
                         q:=f(i)
                         q=false => return false
              return true
      r:NNI:=x
      r=2=>true
      false

h(b:List Any):Boolean==
    for i in b repeat
          q:=f(i::Union(List(Any),NNI))
          q=false=> return false
    true

(5) -> [[i, m(i)] for i in [ [2],[2,2],[[2],[2,2],2],[],[[],[]] ] ]
   (5)
   [[[2],true],[[2,2],true],[[[2],[2,2],2],true],[[],true],[[[],[]],true]]
                                                      Type: List List Any
(6) -> [[i, m(i)] for i in [ [1],[22],[2,2,2,1], [[1,2],2] ]  ]
   (6)  [[[1],false],[[22],false],[[2,2,2,1],false],[[[1,2],2],false]]
                                                      Type: List List Any

Perl 5, 26 bytes
25 bytes of code + 1 for -n
map$.&=$_==2,/\d+/g;say$.

Try it online!

TXR Lisp, 30 bytes
(opip flatten(all @1(op = 2)))

Run:
1> (opip flatten(all @1(op = 2)))
#<intrinsic fun: 0 param + variadic>
2> [*1 '()]
t
3> [*1 '(2)]
t
4> [*1 '(2 2 ())]
t
5> [*1 '(() ())]
t
6> [*1 '(() (1))]
nil
7> [*1 '((2) 1 ())]
nil

MY, 6 bytes
⎕ḟ2=Π←

Try it online!
How?

⎕ evaluated input
ḟ flatten
2= element-wise equality with two
Π product
← output with no newline

Common Lisp, 68 64 bytes
(defun n(l)(or(and(consp l)(n(car l))(n(cdr l)))(not l)(= l 2)))

Try it online!

Pyth, 6 bytes
q]2{.n

Try it here!

Jelly, 3 4 bytes
F=2Ạ

Gained a byte because of a failed test case.
Try it online!

This fails on the [[1,2],2] test case.

@ØrjanJohansen Fixed at the cost of one byte.

It is now a dupe of this: https://codegolf.stackexchange.com/a/120371/44874

Arturo, 19 bytes
$=>[[]=--flatten&2]

Try it
$=>[            ; a function
    []=         ; is the empty block equal to...
    --flatten&2 ; the input, flattened, with 2s removed?
]               ; end function

Zsh, 9 bytes
<<<${@/2}

Try it online!
Falsey: output contains a number. Truthy: anything else (spaces or empty string). Link includes a test harness that prints T or F

This doesn't really do nested lists does it? It just seems to be space separated numbers

True, Zsh only does 1-dimensional arrays/lists

Pyt, 4 bytes
Ƒ2=Π

Try it online!
Ƒ           implicit input; Ƒlatten array
 2=         is each element equal to 2?
   Π        product (returns 1 for empty array); implicit print

Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes
r=2

Try it online!
r=2
 =2 # Is each element equal to 2?
r   # Product

Uiua, 8 bytes
/×⬚1/×=2

Try it!
/×⬚1/×=2
      =2  # where are elements equal to two?
  ⬚1/×    # multiply columns, filling missing elements with one
/×        # product

APL(Dyalog Unicode), 9 bytes SBCS
(⊢≡2⍴⍨≢)∊

Try it on APLgolf!
Alternatively, another 9-byte solution:
∧/'2 '∊⍨⍕

Try it on APLgolf!

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Element of string at specified index
Given a string s and a non-negative number n less than the length of s, output the character at the n-th position of s.
0-indexing and 1-indexing are allowed. For 1-indexing, n will be positive and less than or equal to the length of s.
s will consist of printable characters only.
Any reasonable input/output is permitted. Standard loopholes apply.
Testcases (0-indexing):
n s        output
0 "abcde"  a
1 "abcde"  b
2 "a != b" !
3 "+-*/"   /
4 "314159" 5

Testcases (1-indexing):
n s        output
1 "abcde"  a
2 "abcde"  b
3 "a != b" !
4 "+-*/"   /
5 "314159" 5

This is code-golf, so shortest answer in bytes wins.

I downvoted this because it's not really a programming or golfing challenge; all that's essentially being asked here is which language has the shortest built-in for the job.

@Shaggy Same for many other simple challenges like adding two numbers, testing if a number is prime or printing "Hello, World!". While these are boring in many languages that can do them out of the box, they can be interesting challenges for more primitive languages that have to roll their own implementation. Plus, anything more complicated is usually too much to ask of those languages, so it's nice to have an outlet for them. If trivial challenges bore you, try doing them in a nontrivial language.

MATL, 1 byte
)

Try it online!
Well, hard to make it much simpler. ) indexes the first input, using the second input value. This is 1-indexed.

Alice, 5 bytes
I&IO@

Try it online!
As usual it's much shorter if we avoid Ordinal mode and use an abysmal input format. Here, the first character's code point is used as the integer input. The remainder of the input is the string. The index is 1-based.
Explanation
I   Read a character and push its code point.
&I  Read that many more characters and push them.
O   Output the last one we read.
@   Terminate the program.

abysmal - I thought you made it xD

@StephenS You mean I proposed this I/O format on meta? Yeah, I did, but mostly for languages that would have to implement their own decimal integer parser/renderer each time they compete in a challenge with numerical I/O, so they would likely just skip those entirely. But it has the unfortunate side effect that in some languages which can read and write decimal quite easily it's still shorter to use code points instead.

Python, 15 bytes
str.__getitem__

or
lambda s,i:s[i]

Both take 2 arguments: the string and the index. 0-indexed.

I'm surprised both methods have the same length.

Haskell, 4 bytes
(!!)

0-based indexing. Usage example: (!!) "Hello" 1-> 'e'.

Octave, 10 bytes
@(s,n)s(n)

Takes a string s, and a number n as input, and returns the nth character of s.

Retina, 28 20 19 bytes
Saved 8 bytes thanks to @MartinEnder by not using balancing groups
Saved 1 byte thanks to @mbomb007 by using ^.+ instead of ^\d+
^.+
$*
+`1¶.
¶
!1`.

Try it online!
The program is 0-indexed.

Change \d to . to save a byte.

@mbomb007 Thanks for the tip :)

05AB1E, 1 byte
0-indexed.
è

Try it online!

CJam, 3 bytes
{=}

Try it online!
= is the built-in for list/string indexing.

Alice, 10 bytes
/@!O?]&
 I

Try it online!
Expects the string on the first line and the 0-based index on the second line.
Explanation
Despite its wealth of built-ins, string indexing doesn't exist in Alice. The reason is that it requires both an integer and a string parameter, and all commands in Alice are strictly integers to integers or strings to strings.
In general, the main way to perform any operations on strings that require or result in integers is to store the string on the tape in Ordinal mode, which you can then manipulate with integers in Cardinal mode.
/    Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP bounces
     diagonally up and down through the program.
I    Read one line from STDIN and push it.
!    Store the string on the tape. This writes the character codes into consecutive
     tape cells starting at the tape head. (It also writes a -1 at the end as a
     terminator, but the tape is initialised to -1s anyway).

     The next few commands are junk that luckily doesn't affect the program:

?      Load the string from the tape and push it to the stack again.
&      Fold the next command over this string. That is, for each character
       in the string, push that character, then execute the command.
?      So we're folding "load" over the string itself. So if the string is "abc"
       we'll end up with "a" "abc" "b" "abc" "c" "abc" on the stack.
!      Store the top copy of "abc" on the tape (does nothing, because it's
       already there).

     Now the relevant part of the program continues.

I    Read another line from STDIN, i.e. the string representation of the index.
/    Reflect to W. Switch to Cardinal. The IP wraps to the last column.
&    Implicitly convert the string to the integer value it represents and
     repeat the next command that many times.
]    Move the tape head right that many cells. Note that Ordinal and Cardinal
     mode have separate tape heads, but they are initialised to the same cell.
?    Load the value from that cell, which is the code point of the character
     at the given index.
O    Print the corresponding character.
!    This discards or converts some of the strings on the stack and writes some
     value back to the tape, but it's irrelevant.
@    Terminate the program.

"Despite its wealth of built-ins, string indexing doesn't exist in Alice." >_>

@LeakyNun If you think that's bad, there's also no built-in to get a string's length. ;)

Prolog (SWI), 40 37 bytes
q(L,N,A):-nth0(N,L,X),char_code(A,X).

Try it online!

Cubix, 8 bytes
t@poIA//

This solution is 1-indexed. The input should consist of a number first, then a separator (that is not a digit or a .) and then the string.
Try it online!

Jelly, 1 byte
ị

Try it online!

Brachylog, 2 bytes
∋₎

Try it online!
Explanation
∋ unifies its output with an element of the Input. With ₎ as subscript, it will unify its output with the Ith element of S, with [S,I] as input.

Japt, 2 bytes
gV

This solution is 0-indexed.
Try it online!

JavaScript, 11 10 bytes
s=>n=>s[n]

Uses 0-based indexing.
-1 byte thanks to @Leaky Nun

f=
s=>n=>s[n]
console.log(f("abcde")(0));
console.log(f("abcde")(1));
console.log(f("a != b")(2));
console.log(f("+-*/")(3));
console.log(f("314159")(4));

you can use currying s=>i=>s[i] to save a byte

Every time I see answers like this it annoys me because I know the C# version is always one byte longer for the semi colon on the end. And that is indeed the case here

Carrot, 16 bytes
$^//.{#}/S1//.$/

Try it online!
The input format is as such:
string
index

And the program is 1-indexed.
Explanation
Carrot has several global variables, one for each type: string, float and array (others to be implemented soon). The program starts in string-mode, where all the operators will affect the global string variable. And I call these variables the "stack".
(Example input: abcdef\n3)
$                          Get the first line of the input and set the stack-string to this value
^                          Exit caret-mode
                           stack-string = "abcdef"
/                          Operator (behaves differently depending on the argument)
 /.{#}/                     And the argument to this operator is a regex, so this program gets the matches of this regex into the stack-array
  .                          Any character
   {#}                       Pops a line from the input. So now this evaluates to # of any character where # is the second line of the input (in this case, 3)
                           stack-array = ["abc"]
                           And now we just need to get the last character in this string, but first
S1                         Join the array on the number 1 and set this to the stack-string. Because the array only contains one element, the number 1 does not appear in the stack-string.
                           stack-string = "abc"
/                          Operator; because the argument is a regex, this retrieves the matches of the regex:
 /.$/                       Get the last character in the string
                           stack-array = ["c"]

Now this returns a one element array containing a string of length one, but it is shown as a string in the website.
If we really wanted to give the result as a string, we could easily do S"," at the end, but it doesn't matter because the output still looks the same on the interpreter.

><>, 13 + 1 = 14 bytes
+1 for -v flag to take input
:?!\i~1-
io;\

Thanks to @steenbergh for notifying me about the -v flag and saving me 3 bytes!
Input the index with the command line argument -v [index] (0-indexed) and input the string through stdin.
Try it online!
Explanation
The stack starts with the index on top.
: duplicates it.
? ignores the next character if the index is 0. (Popping it off the stack)
If it is zero, \ reflects the direction to go down. Then, it is reflected to the right with the next \. It wraps around and executes input a character, output it and ; halts execution.
If not, ! skips the next instruction, so it doesn't go down.
i~ inputs a character and then immediately discards it.
1 pushes 1.
- subtractes 1 from the index, so one character in the input is consumed and the index is decremented. The program loops around back to the :.

There is the -v <x> command line parameter, which initialises the stack to hold <x> on program start. Try it online

S.I.L.O.S, 43 bytes
loadLine
readIO
a=256+i
a=get a
printChar a

Try it online!
Simple enough.

SILOS is back \o/

Yeah,  I'm trying to answer as many callenges as possible, including the windows loading screen one. I like the point it's at in terms of graphical output, and libraries, but I still would like to develope a compression scheme to try and get it competitive. Essentially the int[] it compiles to can be generated through reading a byte stream. @LeakyNun

BF, 9 bytes
,[->,<]>.

The index is taken via the character code of a char (like the Alice submission). Following that, we have the string.
Try it online!
The TIO link uses a Bash wrapper and the input can be changed in the header file (the reason for the wrapper is so that we can see the bytes).

Legit TIO hacking :p

@LeakyNun I used the wrapper for BF.

I did say it is legit.

Is there a way to do input to other TIO languages like that? Like SMBF?

@mbomb007 You should be able to do that for other languages by using their wrappers. Here's the wrapper for SMBF

Is there a way to put unprintables in the source code using a method like that. Like .code instead of .input?

Clojure, 3
nth

:P What can you do when there is a built-in for this? This works on lists, vectors, strings and sequences. It is either O(1) or O(n), depending on the used datatype.

Batch, 32 bytes
@set/ps=
@call echo(%%s:~%1,1%%

Reads s from STDIN and takes n as a command-line parameter.

GolfScript, 7 4 bytes
~1/=

Try it online!
I suck in GolfScript, so I value Martin Ender's help.

There's no need for the [.

But in general if you want characters from strings, you just split the string first instead of converting the code point back: ~1/=

@MartinEnder And that's how you beat Alice up...

Turtlèd, 9 bytes
!?:[*l+].

Try it online!
explanation:
First off, Turtlèd is grid based, with a turtle thing. There are grid cells the turtle can move left, up, down, and right on, and can write things on the grid cells.
[the first grid cell the turtle starts on is marked with a *]
!         input the string into the string variable

 ?        input the number into the number variable

  :       this command takes the number variable and moves right that many.
          hence this moves right by the amount inputted

   [*  ]  this is an `until` loop. the * there means that `until` the turtle ends the loop
          on a grid cell with * written on it (that is, the first cell), it will execute
          the code inside again and again

     l+   the code inside the while loop. the `l` moves the turtle left, and the +
          increments the string pointer. the string pointer is used with the string var;
          when you want to write something from the string, you use `.`, which writes
          the pointed char. the pointed char is the n-th character of the string, n being
          the value of the string pointer. this code will execute until the l moves
          the turtle back on to the origin cell. since we moved right by the number
          inputted, this will increase the string pointer (which starts at 1)
          by the amount inputted.

       .  write the pointed char, which was dealt with in the previous comment.
          if 0 is inputted, turtle stayed on the origin square, and executed none
          of the loop, and turtle writes the first char of string input.
          if 1 is inputted, turtle moved one right, moved one left and incremented
          string pointer once, which means the second char is written. and so on.

          [the char of input has been written over the origin square]
          [implicitly the grid is outputted, which has spaces and blank lines taken out]
          [this is the requested char outputted, plus an unavoidable trailing newline
          due to how I made the interpreter. sue me]

sed, 31 bytes
:
/^1/{s:1 .: :;b}
s: (.).*:\1:

Try it online!
Input: index and the string, separated by one space. Index in unary, but zero-based.

Axiom, 1 byte
.

1-Indexing... string.index is the value of string at index
some test
(5) -> "123".6
   >> Error detected within library code:
   index out of range
    protected-symbol-warn called with (NIL)

(5) -> "123".0
   >> Error detected within library code:
   index out of range
protected-symbol-warn called with (NIL)

(5) -> ["123".i  for i in 1..3]
   (5)  [1,2,3]
                                                     Type: List Character

Where you see Axiom warn for index out of space too

Snippets are not allowed. Only functions/full programs are allowed.

@LeakyNun I can not see it as operator? (and so one function)

A function is which you can give a name to. Would f=. make sense?

@LeakyNun that operator has already a name '.' Why I have to call in a different way?

@RosLuP to be a valid answer in a challenge with I/O, you have to have a program that reads input, or a function that gets passed input as parameters and returns output. I don't know axiom, but see my JavaScript answer - it will probably look similar.

@StephenS We're accepting the names of built-in functions as function submissions, so I don't see why we shouldn't accept the names of built-in operators (which are functions, just usually with different syntax).

@MartinEnder, I agree with that reasoning, but where should the line be drawn? Should operators that have added syntactic sugar be allowed as well? Python's a[b] is just syntactic sugar for str.__getitem__(a,b), for example; if . is a valid solution here, should [] be a valid solution in Python and other similar languages? I'm probably overlooking some obvious difference between the two cases, but none comes to mind immediately.

@JulianWolf It might be good to settle this debate on meta. (I don't have the time to write up a post right now though.)

I think we've already discussed a lot of related questions on Meta (although I haven't found one that addresses this situation specifically), and IIRC a function submission has to be a function value. So in Haskell, for example, + isn't a valid solution to "add 2 numbers", but (+) is.

@ais523 Found it. You're essentially right.

Dyvil, 4 Bytes
_[_]

Creates an anonymous function that takes a String and an int and returns a char.
Usage:
let f: (String, int) -> char = _[_]
print f("abc", 1) // b

Pip, 3 bytes
a@b

This is 0-based. Try it online!

QBasic 4.5, 24 bytes
INPUT a$,b:?MID$(a$,b,1)

Pretty straightforward.

Vim, 8 bytes
DJ@"|xVp

Since V is backwards compatible, you can Try it online!

Java 8, 18 17 12 bytes
s->s::charAt

-5 bytes saved thanks to @Jakob.
Try it here.
Java 7, 43 bytes
char c(String s,int n){return s.charAt(n);}

Try it here.
Both 0-indexed.

Can you use currying i.e. s->n->... to save a byte? And does Java not have indexers i.e. s[n]?

@TheLethalCoder Yes, and no. Was indeed just trying to write the currying answer in TryItOnline. But since I've barely used Java 8, I'm a bit unsure how to go about it. But you're indeed right that currying saves a byte, was about to change it. As the s[n]. String is an Object, so you can do things like s.equals(...) and s.charAt(...) to s.toCharArray(). With an array you are able to do [n], like int a=new int[]{1,2,3,4}; int result = a[0]; // <- a[0] = 1

In C# you'd do Func<string, Func<int, char>> so something similar I assume.

@TheLethalCoder You're indeed right, should have a working TIO now.

Since you're already currying, save another 5 bytes with a method reference: s->s::charAt.

@Jakob Could you perhaps create a TIO. I'm tbh not entirely sure how I can combine currying and a method reference at the same time.. I only use Java 8 for golfing, and Java 7 kind of methods in day-to-day work.

Sure! It's a simple change: TIO

The method reference essentially extracts the charAt method from String s. s::charAt has the same type as your inner lambda: Function<Integer, Character>.

k (kona), 0 bytes (noncompeting); 1 byte
In K, list access (as function application) is implicit. As such, we can do
q)"abcdef"0
"a"

But that's not really in the spirit of things, so we'll make the application of 0 on "abcdef" explicit for 1 byte:
q)"abcdef"@0
"a"

TI-Basic, 14 bytes
Prompt Str0,N
sub(Str0,N,1

Returns the Nth 1-indexed character of the string.
Noncompeting 10 bytes:
Prompt N
sub(Ans,N,1

run with: "string":prgmNAME then input the number. I can't see the upvote/downvote ratio of this meta post on whether different input types are allowed, and it doesn't say in the tag-wiki, so I'm assuming they aren't.

brainfuck, 17 bytes
...because why not?
,[,>+<-]>[<,>-],.

Try it online!
Uses 0-indexing, takes number in unary, n separated from s by .
This separates n from s with a newline.

Ruby, 9 bytes
proc &:[]

How Ruby handles operator overloading is :+, :-, :*, :[], etc. are defined as methods, so 1+2 is essentially 1.+(2). :[] is the symbol for the subscripting "operator", which when converted to a proc calls the :[] method with the first as a receiver and the second as an argument. E.g., (proc &:[]).call("asd",0) == "asd".[](0) == "asd"[0]

J-uby, 3 bytes
:[]

[] is the subscripting operator. Example run:
irb(main):001:0> f = :[]
irb(main):002:0> f.call("string", 2)
=> "r"

Mathematica, 18 bytes
#~StringTake~{#2}&

Basic solution, but unfortunately the function name is quite long.

C#, 11 bytes
s=>n=>s[n];

Python 3, 28 bytes
print(input()[int(input())])

Integral, 2 Bytes
Integral doesn't have an a[n] built-in. Unfortunately it does have some slicing built-ins, which makes a 2-byter possible...

rn

Try it!
Explanation
r   Last b
 n  Head

Factor, 3 bytes
nth

Try it online!

Vyxal, 1 byte
i

Try it Online!
Can't get much simpler than this.

Thunno 2, 1 byte
i

Attempt This Online!
Built-in.

C, 18 Bytes
#define f(s,n)s[n]

Try it online

PHP, 22 Bytes
<?=$argv[1][$argv[2]];

Try it online!

Swift - 53 bytes
func f(a:String,i:Int){print(Array(a.characters)[i])}

A function f that can be used as f(a: "abcdef",i: 3). It is 0-indexed.
Check it out!

QBIC, 8 bytes
?_s;,:,1

Explanation:
?     PRINT
_s    Substring(in$, start, length)
  ;   Reads a string from the cmd line as in$
  ,:  Reads an int from the command line as start
  ,1  One character
      Statement delimeter | is auto-added at EOF.

This is 1-based. It uses QBIC's new ability to inline ; and :. Previously, to get s and n, you needed to do this:
;:?_sA,a,1

That would create the assignment of a cmd line arg to A$ and a resp. Now we can skip assignment: the interpreter extracts the assignment and moves those to the top of the script.

Fireball, 3 bytes
1-indexed.
╡1╞

Explanation:
╡         Get the first n characters of the input
 1╞       Get the last character of the that

Alternatively, for 4 bytes:
╡r↔♥

Explanation:
╡      Get the first n characters of the input
 r     Reverse
  ↔♥   Get the first character

Perl 6, 18 bytes
{substr $^a,$^b,1}

I'm a little surprised it can't be done shorter.  By me, anyway.

could you remove the space before the first $? Not too familiar with Perl

Nope.  Perl 6 requires whitespace in many places that Perl 5 doesn't.

that seems very un-Perl-like if that's a thing

Charcoal, 3 bytes
§ＳＮ

Explanation
§     At index
 Ｓ   Input string
   Ｎ Input number

Try it online!

APL (Dyalog), 1 byte
⌷ (Index) or ⊃ (Pick)
Try them online!
They only differ for higher rank arrays and nested arrays:
2⌷A will choose the second element or second row, leaving any nesting
2⊃A will pick the second element, and attempt to remove one level of nesting
2 3⌷A will choose the element at row 2 column 3
2 3⊃A will pick the third element of the second element
(⊂2 3)⌷A will choose the second and third elements or rows
(⊂2 3)⊃A will pick the element at row 2 column 3

Chip, 114 bytes
*Z
,x.z.
`@z\{Aa
,x.|*
`@z\{Bb
,x.|
`@z\{Cc
,x.|*
`@z\{Dd
,x.|
`@z\{Ee
,x.|*
`@z\{Ff
,x.|
`@z\{Gg
,x.|*
`@z\{H
S{*

The first byte of input is a 0-based index, the remainder is the string to process: \x02abcde.
Try it online!
In this TIO, a newline character is the index, which means an index of 0x0a = 10.
Test cases!
These use hex input + printf to make it clearer what's happening.
How does it work?
S{*
This suppresses output for all bytes, by default. If powered, this can be overridden. It is a not-gate based on an xor-gate ({).
Aa, Bb, Cc, etc.
These relay the input to the output for every byte, unless suppressed. Note that the h is missing, this is because we never need to output something with the high bit set.
,x.
`@z\{D

This is the real meat of it all. There are eight of these, one for each bit of the index (a one-byte index means that indexes are not able to be specified above 255). This reads in the index on the first cycle only with switches (\). The index bits have been flipped with an xor gate ({), which is almost negation. Then, for each character of the string, this value is incremented via some half-adders (@). When this value is incremented from 0xff to 0x00, it uses the carry from the high bit to unsuppress output for that character, meaning that it is printed.

Ruby, 11 bytes
->n,s{s[n]}

Try it online!

proc &:[] is shorter :P

Pyth - 3 bytes
@wE

Try it here

RProgN 2, 1 byte
ü

Just a builtin!
Try it online!

SmileBASIC 3, 17 bytes
Woo! String indexing!
DEF A S,N?S[N]END

Defines a command A to print the result. Uses 0-indexing. Call like A "string",number.
No string functions, 29
Here's one that uses absolutely no string-specific built-ins.
DEF A S,N
COPY T$,S,N,1?T$END

COPY is a memory copy command, capable of copying data between two compatible types. It's usually used for arrays, but it works on strings as well.

tcl, 18
string index $s $n

Input is on the variables s and n
Output is the return of the script
demo — Iterates a list with all test case pairs and outputs them to console.

Axiom,61 bytes
f(s:String,n:PI):Union(Character,Complex INT)==(n>#s=>%i;s.n)

1-Indexing; it return the required char or it return the  %i=sqrt(-1) for error if n> lenght(s)
Some test
(4) -> [f("123",i) for i in 1..10]
   (4)  [1,2,3,%i,%i,%i,%i,%i,%i,%i]
                              Type: List Union(Character,Complex Integer)
(5) -> f("123", 0)
   Conversion failed in the compiled user function f .
   Cannot convert from type Integer to PositiveInteger for value
   0

instead of doing less (few characters) instead of do more (more cicle) instead to do fast... to do the right

LLVM IR, 72 bytes
define i8*@a(i8*,i64){
entry:%2=getelementptr i8,i8*%0,i64%1
ret i8*%2
}

Takes a (string, index) (0-indexed) as argument, where string is a c-string. Returns an i8* (char*) which points to the desired char. I can't directly move the getelementptr with the ret instruction as %0 and %1 are function-local and therefore need their own instruction
Try it online!

PowerShell, 18 Bytes
param($s,$i)$s[$i]

indexes into param 1 ($s) using param 2 ($i)

Perl 6, 15 bytes
{$^s.comb[$^n]}

Try it
Expanded:
{ # bare block lambda with placeholder parameters ｢$n｣ and ｢$s｣

  $^s      # declare second parameter
  .comb\   # split it into graphemes
  [ $^n ]  # get the value indexed by the first parameter
}

Groovy 11 bytes
{s,n->s[n]}

0-indexed.

Julia 0.6.0 (13 bytes)
f(s,n)=(s[n])
s is a string, n the index. Pretty simple since Julia considers strings as arrays so I just call the index in the array. Julia is a 1 indexing.
Try it online!

Cubically, 18 16 bytes
$:7~(~*1-1/1)6@7

(1-based index)
Input format is n abcde, where n is the index, and abcde is the string.
How it works:
$:7              Get numeric input and set notepad to it
   ~             Skip next character (the space)
    (       )6   Do while the notepad is nonzero
     ~           Get next character of input
      *1-1/1     Subtract 1 from notepad (found by Kamil Drakari)
              @7 Output the current input character

Try it online

Excel, 13 bytes
=MID(B1,A1,1)

1-indexed n in A1.
Text in B1.

Husk, 1 byte
Another built-in, 1-indexed:
!

Try it online!

x86 Machine Code, 13 bytes
8B 44 24 04 03 44 24 08 8A 08 8A C1 C3

Which disassembles to:
  00000000: 8B 44 24 04        mov         eax,dword ptr [esp+4]
  00000004: 03 44 24 08        add         eax,dword ptr [esp+8]
  00000008: 8A 08              mov         cl,byte ptr [eax]
  0000000A: 8A C1              mov         al,cl
  0000000C: C3                 ret

T-SQL, 29 bytes
SELECT SUBSTRING(s,n,1)FROM t

Input is taken via a pre-existing table t with integer n and string s, per our IO standards.

Rebol, Red 4 bytes
s/:n

(need to make body at least 30 to satisfy submission nanny)

Hello and welcome to PPCG. You can use the HTML comment tag <!-- ... --> to fulfill your post length needs. Also, I would suggest using a # markdown or HTML header tag to start your post with a header.

Rather than adding markup comments, consider adding an explanation to your answer on how your program works. This will improve the quality of your answers and make it more likely that it will attract upvotes.

MathGolf, 1 byte
§

Try it online!
Finally a showcase for the implicit input! Works regardless of the order of the input (if the string or int comes first).

Acc!!, 85 bytes
N
Count i while _/128^i/32 {
_+128^(i+1)*N
}
Count j while N/48 {
_/128
}
Write _%128

Takes the string on one line of stdin and the 0-based index, in unary, on the following line. (I hope unary is okay. Decimal I/O is a pain in Acc!!) Try it online!
Commented
# Read printable ASCII characters into the accumulator, storing the first character
# in the least significant place
N
Count i while _/128^i/32 {
_+128^(i+1)*N
}
# Read 1s, shifting the accumulator down by one character's worth each time
Count j while N/48 {
_/128
}
# We have now removed the first i characters from the original input string,
# which means the first remaining character is the one at index i (0-based)
Write _%128

Perl 5 -plF, 9 bytes
$_=$F[<>]

Try it online!

Befunge-98 (FBBI), 5 bytes
1-indexing. Input is the index, a space and the string.
&k~,@

Try it online!
This just reads index characters as input and prints the last one.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Sigmafy the expression
For those who didn't know, Sigma  is a Greek letter which is heavily used in mathematics as the summation sign. Given a string representing an expression depending on \$k\$ that we will denote \$E(k)\$, compute the sum of the results for \$E(k)\$, for each \$k\in\{1,2,3,4,5\}\$. Concisely, you should find \$S\$ such that:
$$S=\sum^5_{k=1}E(k)$$
An example of an expression: \$E(k)=\frac k 2 + k^2\$

Specs

You are guaranteed:

that the expression is valid, so it contains no errors, and that it's dependent of the syntax chosen (e.g: if you only support 2*k, there will be no 2k)
to only have defined values amongst your results, so no values like 1/0, inf or nan will appear

You can assume that the expression above is fitting the limits of the programming language of your choice, so it won't result in overflows or any other limit-related errors
Any other non-whitespace ASCII Character instead of k can be chosen
Your program must support the following operations:

addition (+, plus(),add(),sum())
subtraction (-, minus(), subtract())
exponentiation (**,^,pow() or others, should be specified), with support to negative bases and exponents
square root in the form of sqrt(k), k^0.5, k**0.5, or however else you wish
multiplication and division

The submission can either be a full program or a function, while mentioning its usage
Any trailing / leading whitespace is allowed when outputting
Minimum precision: 2 decimal places

Test Cases (with k)
+---------------+--------------+
|  Input = E(k) |    Output    |
|---------------+--------------|
|2*k            | 30           |
|---------------+--------------|
|sqrt(k)        | 8.38         | (* with minimum decimal precision)
|---------------+--------------|
|k+k/2+k**2     | 77.5         |
|---------------+--------------|
|k**2           | 55           |
+---------------+--------------+

The score will be the number of bytes (of the source + compiler flags). The lowest scoring valid submission wins, while taking note that these loopholes are strictly forbidden. Here is a Python pseudo-code, to make things clearer.

Can we take plus() instead of +? (Same questions for all other operators too)

@StewieGriffin Yes, plus(),add(),sum() and equivalents are allowed. See the edit.

No, you may only take the expression once, @ComradeSparklePony

Can we use postfix notation? For example, test case 3 from the top would be something like: N N2/+N2**+.

That's very strange, but it is allowed as long as you clearly state the "format" of E(x) @ComradeSparklePony

@Mr.Xcoder That isn't very strange. There are languages which use the postfix notation, as well as languages which use the prefix notation. Putting those expressing in our native notation makes eval easier.

@LeakyNun yes, I have totally understood the purpose, and thus have allowed it, but I said that it's strange for the tester, not to the author.

Does the program need to support multiplication and division? It's in the test cases, but not in the specs.

Oh yes, sorry @pajonk yes, it must.

Borderline dupe

Do you really think this is a dupe @PeterTaylor ? I would say it is loosely related.

IMO the hard work is parsing the expression. Substituting a value for the string k and looping from 1 to 5 are pretty trivial in comparison. The main reason I didn't actually vote to close is that it's not clear what range of parameters for ^ the other question requires, so I don't know whether sqrt is covered.

@PeterTaylor that one also restricts using eval, that's why I say it is just related

Can we take something like expression(k+k/2+k**2) as input instead of a string?

@JayCe Like taking a black-box function representing the expression E(k) and just doing sum(map(E,1...5)) (pseudo-code)? If so, no.

Jelly, 5 bytes
vÐ€5S

Try it online!
Input a valid Jelly monadic chain (I golfed them down in my link).
How it works
vÐ€5S
 Ð€     for each of ...
   5        5 (implicitly converted to [1,2,3,4,5]), ...
v           evaluate the input with the above as argument
    S   and find the sum

Mathematica, 17 14 13 bytes
Thanks to Ian Miller for saving 3 bytes.
Thanks to LegionMammal978 for saving 1 byte.
#~NSum~{k,5}&

The input should be an actual expression containing k, e.g.:
#~NSum~{k,5}&[Sqrt[k]^3+4]

I should have guessed that Mathematica had built-ins for this

Mathematica always has built-ins for situations. :P

You don't need the 1, in it for Sum.

In fact it can shorten to N@#~Sum~{k,5}&

@IanMiller Oh right, of course. Thank you!

I believe that #~NSum~{k,5}& should also work.

@LegionMammal978 It does, thank you. :)

Python 3, 40 37 bytes
3 bytes thanks to Arnauld.
Eval scope tricks \o/
f=lambda s,k=5:k and eval(s)+f(s,k-1)

Try it online!
Uses k**0.5 instead of sqrt(k).

Is it allowed to answer a question that fast? o_O

JavaScript (ES7), 31 30 bytes
Uses k**0.5 for sqrt(k).

f=(e,k=6)=>--k&&f(e,k)+eval(e)

console.log(f("2*k"))
console.log(f("k**0.5"))
console.log(f("k+k/2+k**2"))
console.log(f("k**2"))

Try it online!

Ninjaed again! Nicely done.

05AB1E, 8 7 6 bytes
6G¹.VO

Try it online!
Input is in postfix notation, and uses the variable N. 05AB1E is a stack-based language, so only postfix notation works.
Format of E(N): write the number(s) you want to do the operation with, and then write the sign of the operation. For example, 3+4 would be 3 4+, 3*4+2*3 would be 3 4* 2 3* +. Also note that this uses t instead of sqrt, and m instead of **, so sqrt(N) would be Nt.
Explanation:
6G¹.VO
6G     For N in range(1,6). This includes [1,2,3,4,5].
  ¹.V  Read and eval input.
     O Sum results.

Octave, 50 46 31 29 bytes
@(d)eval(["k=1:5;sum(" d 41])

Try it online!
Exponentiation is denoted with the caret .^ and multiplication is denoted with .*.
This declares an anonymous function that takes in argument d. It sets k to be equal to the range 1:5 and sums the evaluated d and returns it.

Japt, 10 bytes
6ÆK=XOxUÃx

Input string should have variable as an uppercase K. sqrt(K) should be inputted as K**0.5.
Try it online!
Explanation
eval scope didn't work in my favor; had to redefine the counting variable X as a global K.
6ÆK=XOxUÃx      // implicit: U = input string
6oXYZ{K=XOxU} x // expanded

6oXYZ{      }   // create array [0, 6) and map to function:
      K=X       //   redefine the array value to global K
         OxU    //   eval the input string
              x // sum the resulting array

Hmm, I wonder if transpiling Ox directly to eval( would help with that...

Octave, 25 23 bytes
@(f)sum(inline(f)(1:5))

Try it online!
Exponentiation is denoted as .^

APL (Dyalog), 9 bytes
+/⍎⎕⊣k←⍳5

Try it online!
Addition is +, subtraction is -, multiplication is ×, division is ÷ exponentiation is * and execution is right to left, so use () to group expressions.
Input is in terms of k.
Explanation
k←⍳5                    Set k to be equal to the vector 1 2 3 4 5
⊣                       The left argument:
+/                      Sum of
⍎⎕                      The evaluated input (the eval returns an array because k is an array)

And here's a solution that takes trains as input (like the Jelly answer): +/(⍎⎕)¨⍳5.

Common Lisp, 55 bytes
(defun f(x)#.(read))(print(+(f 1)(f 2)(f 3)(f 4)(f 5)))

Try it online
Example input - output:
(* x 2) - 30
(sqrt x) - 8.382333
(+ (/ x 2) x (expt x 2)) - 155/2
(expt x 2) - 55

different, longer (58 bytes) version - starts getting shorter if you do sumation from 1 to 7.
(print #.`(+,@(mapcar #'(lambda(x)#.(read))'(1 2 3 4 5))))

yet another and longer method (65 64 bytes) - doesn't define function - just inserts your expression into a loop. Should get shorter for bigger sums.
(setf a(read)b 0)(loop as x from 1 to 5 do(incf b #.a))(print b)

Swift, 202 184 bytes
import Foundation;func s(i:String){print([1,2,3,4,5].map{NSExpression(format:i.replacingOccurrences(of:"k",with:"\($0).0")).expressionValue(with:nil,context:nil)as!Float}.reduce(0,+))}

For some reason this will only run locally :(.
Here is an explanation of what I am doing:
import Foundation // Import the Foundation module

func s(i:String){ // Create a function that takes in a String and returns a Float

    print( // Print the result of the follow algorithm to strdout

        [1,2,3,4,5].map{ //Conduct the follow code on numbers 1 - 5

            NSExpression(format: // Create an expression with the following String and return it

            i.replacingOccurrences(of:"k",with:"\($0).0")) // Create a string replacing all ocurrances of 'k' in `i` with the current Float from the map

           .expressionValue(with:nil,context:nil)as!Float // Get the resulting value of the expression

       }.reduce(0,+) // Add the result of all the expressions together
    )
}

Thanks to @Mr. Xcoder for saving 15 bytes!

TI-Basic, 12 bytes
Σ(expr(Ans),K,1,5

Call with "string":prgmNAME, where string is any valid TI-Basic expression of K.

Interesting solution of the same length: Ans->u:sum(u(1,5

Stacked, 16 bytes
5~>[@k#~]2/"!sum

Try it online!
5~> is a range from 1 to 5 incluive. 2/ makes a func dyadic, " is pair-wise, and ! is execute. This thus maps the range [1, 5] with the input, which is then evaluated after defining the range member to be k. Then, the results are summed.

dc, 31 24 bytes
?sa1k[lax+Kd1+k5>p]dspxp

The input must be given in reverse-Polish notation (also known as postfix notation) and enclosed in square brackets ([]) with:

K replacing k as the parameter;
+ representing addition;
- representing subtraction and _ followed by any number representing a negative number;
* representing multiplication;
/ representing division;
^ representing exponentiation;
v representing the square-root.

For example, -2*k+k+3*k**2+k**0.5-k/2 would be input as [_2K*K+K2^3*+Kv+K2/-]. This takes due advantage of the fact that K is a dc command which returns the current precision (initially set to 1). Therefore, by the end, this returns the output with a precision of 6.
Try it online!

Tcl, 58 bytes
proc S {f s\ 0} {time {incr k
set s [expr $s+$f]} 5
set s}

Try it online!
If it only worked with integers, I could golf it more!

R, 35 bytes
k=1:5;sum(eval(parse(t=scan(,""))))

Try it online!
TIO link includes a function solution as well (38 bytes)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/