Comparisment

   - compare programming languages by example

54

List slices

Slice sections of a list.

Created by sam

Add a new answer

Either add an answer for a new language or add an alternative solution.
A description is only necessary when the code is not suitably 'obvious' or to justify an alternative approach.

Haskell

slice :: Int -> Int -> [a] -> [a]
slice from to xs = take (to - from + 1) (drop from xs)

No sugar for list slicing exists. A definition similar to above can be written, noting its performance will be O(to).

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

firstTen = range(0,10)

start = 0
end = 5
firstFive = a[start:end]

Slice a list between two indexes.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

firstTen = range(0,10)

start = 5
lastFive = a[start:]

Slice a list after an index.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

firstTen = range(0,10)

end = 5
firstFive = a[:end]

Slice a list before an index.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

firstTen = range(0,10)

end = -5
firstFive = a[:end]

Slice before an index that counts from the end of the list.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

firstTen = range(0,10)

start = -5
lastFive = a[start:]

Slice a list after an index counting from the end of the list.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

firstTen = range(0,10)

firstTenAgain = firstTen[:]

With no index(/s) given, the entire list is copied.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

firstTen = range(0,10)

start = 0
end = 10
step = 2

firstTenEvens = firstTen[start:end:step]

Slice between a start and end point with a step.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

firstTen = range(0,10)
step = -1
reversedTen = firstTen[::step]

A negative step can be used to reverse a list.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.