DEV Community

Cover image for Comparing "SLICE" in Python and Go-lang.
myk_okoth_ogodo
myk_okoth_ogodo

Posted on

Comparing "SLICE" in Python and Go-lang.

In this new series i will be talking about data structures in two of the biggest back-end languages Go-lang and Python. I intend to look at a data structure that are common to both languages, comparing their implementation, speed, methods, commonalities and differences in the two languages.
Python and Go-lang both find a heavy use cases in today's server-side application development, with python particularly shinning through its most popular frameworks, Django, Flask, Tornado . Python as a language also finds solid uses in the following spheres;

  • Data science, using tools like NumPY, Pandas, Matplotlib, Keras.
  • AI applications, using tools like TensorFlow, PyTorch, Keras.
  • Game development, using tools like Pygame, PyKyra, Pyglet, Kivy, Panda3D.

Go-lang on the other hand is a language built for concurrency, it is designed to take full advantage of distributed cloud architectures that are what we mostly use for our current application development and management. Some of its web development frameworks are Gin, Gorilla and Martini. I should probably write a dedicated article comparing the two languages,watch out for this in my next article .
In this first article of the series i am probing what "slice" means in python and go-lang , as we will see in greater detail below, Slice is an in-built python function that returns a slice object that we can initialize with start, end and step indices which can then be used in "slicing" or extracting contiguous elements of our sequences. In Go-lang slice is a mutable data structure that can be used to hold and manage collections of elements of a similar type. Go-lang slices are index-able and can be initialized with capacity and length properties .

Python "SLICE"

In python we have an inbuilt slice() function, that returns a slice object. The slice object in python can only be applied on python sequences.
Python sequences refer to an ordered set that restricts our access of its constituent items to the order in which we input the items. There are six primary types of sequences in python, these are;

  • Strings : an array of bytes representing Unicode characters
  • Lists : a mutable(changeable,malleable) data structure in python made up of an ordered sequence of elements.
  • Tuples : a non-mutable(unchangeable, un-malleable) built-in data structure made up of an ordered sequences of elements.
  • Byte sequences : a mutable(changeable) data structure made up of a fixed-length sequence bytes.
  • Byte arrays : created using bytearray(), is mutable array(sequence) of given bytes in the range 0 and 256.
  • Range objects : created using the range() function, its an immutable sequence of numbers starting from the given start integer to the stop integer. i.e range(start integer, stop integer, step).

The slice() function, takes three arguments,

  • start : The first argument is the index at which to begin the slice operation.
  • stop : The second argument is the index up to(but not including) which to perform the slicing,
  • step : The third argument is the an integer to specify the step of the slicing syntax; slice(start, end, step) if we supply three integer arguments, it defaults to slice(start, stop) when we supply two integer arguments and slice(stop) when we supply one integer argument. Example: Lets assume we have a list sequence of characters below; seq = ["a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" , "i" , "j" , "k" , "l" , "m" , "n" , "o" , "p" ] x = slice(2) #slice(stop), slice from the first index up to but not including the second index, remember sequences in python are zero-indexed print(seq[x]) results in the following output ["a" , "b"] x = slice(2, 6) #slice(start, stop), slice starts from the second index up to but not including the element at index six print(seq[x]) results in the output ["c" , "d" , "e" , "f"] x = slice(2, 8, 2)#slice(start,stop,step), slice starts from the second index up to but not including the element in the eighth index, but skip every second element with each step print(seq[x]) results in the output ["c" , "e" , "g"] colon operator(:) To accomplish the above we can also use the slice operator ,a colon(:), in this case we specify our starting and ending index on either side of the colon i.e sequence[start:end], if we do not provide an end index and only provide the start index i.e sequence[start: ], the slice goes up to last index of our sequence, similarly when we do not provide the start index and only provide the end index i.e sequence[:end], the slicing starts at the first index of our index, to accomplish the above using the colon operator seq = ["a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" , "i" , "j" , "k" , "l" , "m" , "n" , "o" , "p" ] print(seq[0:2]) results in the output ["a" , "b"] print(seq[:2]) results in the output ["a", '"b"] print(seq[2:]) results in the output ["c" , "d" , "e" , "f" , "g" , "h" , "i" , "j" , "k" , "l" , "m" , "n" , "o" , "p"]

print(seq[2:6])
results in the output ["c" , "d" , "e" , "f"]
print(seq[:]) reproduces a copy of the list ["a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" , "i" , "j" , "k" , "l" , "m" , "n" , "o" , "p"]
note: a neat trick to reverse a python sequence using the colon operator is as below
print(seq[::-1])results in the output ["p", "o" ,"n","m","l","k","j","i","h","g","f","e","d","c","b","a"]

Go-lang "SLICE"

In Go-lang a slice refers to an array that can be dynamically sized. Slices are made to hold multiple elements and those elements should be of the same type. A slice data structure can shrink and grow as necessary or as required.
Slices have two properties:
capacity , this is the maximum holding capacity of the slice
length , this is the number of elements currently held by the slice.

syntax
var identifier []type ; where the empty square brackets is our empty slice and the "type" identifies the type of element that the slice will hold:
var myIntegerSlice []int ; creates a slice object to hold elements of type integer
var myStringSlice []string ; creates a slice object to hold elements of type string
Creating a slice using "make":
We can also use the built-in "make" function to create a go-lang slice, "make", allows us to specify the length and capacity of the slice as below;
var myIntegerSlice = make([]int, 20)
The above line of code creates a slice whose length and capacity is equal to 20 integer elements
var myStringSlice = make([]string, 20, 30)
The above line of code creates a lice whose length is 20 and capacity is 30 string type elements.
Creating a slice with initial values:
to create a slice object and initialize it with values at creation time we do the following
var myIntegerSlice = []int{100, 200, 300, 400, 500}
The above code creates a slice called "myIntegerSlice" that is supposed to hold integer values and gives it initial values of 100,200,300,400,500.
var myStringSlice = []string{"this","that","those","them"}
the above code creates a slice called "myStringSlice" that is supposed to hold string values and gives it initial values of , "this","that","those","them"
Appending to a slice:
We can add an item to end of a go-lang slice using the append keyword just like in python where we can also use the same append keyword;
seq := make([]int , 5, 10) // a slice called seq to hold int elements ,with length 5 and capacity 10.
to insert values ;

seq[0] = 10
seq[1] = 20
seq[2] = 30
seq[3] = 40
seq[4] = 50
Enter fullscreen mode Exit fullscreen mode

To append values :
seq = append(seq, 60,70,80,90,100)
Accessing elements of a slice:
We can access the elements of a slice by using indexes of the elements, for example in our sequence "seq" above:
fmt.Println(seq[0]) results in the output 10, fmt.Println(seq[1]) is 20, fmt.Println(seq[2]) is 30 and so on.
Changing the elements in a slice:
In this case we simply use the index to access the element position and change the value held in that position, i.e in our slice seq above;
seq[1] = 200
the seq is now [10, 200, 30, 40,50, 60,70, 80, 90, 100]
Removing an element from a slice:
Using our sequence "seq" above we can remove an element from an index in the sequence as below:
we create our own "removeElemfunction";

func removeElem(seq []int, index int) []int {
return append(seq[:index], seq[index+1:]…]
}
Enter fullscreen mode Exit fullscreen mode

then in our func main;

func main() {
var myIntegerSlice = []int{10,20,30,40,50}
fmt.Println(myIntegerSlice) // prints out [10,20,30,40,50]
myIntegerSlice = removeElem( myIntegerSlice, 3)
fmt.Println(myIntegerSlice) // prints out [10,20, 30,50]
}
Enter fullscreen mode Exit fullscreen mode

"Slicing" a Slice in Go-lang.
Similar to python's slicing of sequences , we can perform a slicing of go-lang slice data type. we use the colon operator in a much similar way to the python slicing discussed above.
For example, lets create a full example that can run, use the go-lang playground to test it.

package main
import "fmt"
func main() {
var bodyParts = []string{"eyes","ears","skin","mouth","nose","hair"}
fmt.Printf("body parts: %v\n", bodyParts)
fmt.Printf(":3 %v\n", bodyParts[:3])
fmt.Printf("2: %v\n", bodyParts[2:])
fmt.Printf("1:3 %v\n", bodyParts[1:3])
fmt.Printf("last body part: %v\n", bodyParts[5])
fmt.Printf("last body part: %v\n", bodyParts[len(bodyParts)-1])
fmt.Printf("copy of the bodyParts sequence : %v\n", bodyParts[:])
}
Enter fullscreen mode Exit fullscreen mode

The results in order of printing are;
body parts : [eyes, ears,skin,mouth,nose,hair]
:3 [eyes,ears,skin]
1:3 [ears,skin]
last body part: hair
copy of the bodyParts sequence: [eyes, ears,skin,mouth,nose,hair]
Similarities between go-lang slice and python list;
1.len

We can get the len of the sequnce using the "len" keyword,
i.e
k = [10,20,30,40,50] //python list
var v = []int{10,20,30,40,50} //golang slice

to get the length of both sequences we ; len(k) in python and len(v)
2. makecopy
Still using the sequences created above in python and go-lang, to make copies using the colon operator;
Kcopy = k[:] // in python
var Vcopy = v[:] // in golang
3. append
Still on the sequences created we can add an element at the end of the sequence i.e;
k.append(60) // in python
k is now [10,20,30,40,50,60]
v = append(v , 60) // in golang

Conclusion

As i have demonstrated above python slice is a built in function that returns a slice object that we can then used to "slice" our sequences i.e lists, strings and tuples, while a slice in go-lang is a data type that is extensible used to implement and manage collections of data its similar to a list data type in python.
Next i will be talking about maps in go-lang and python. Goodbye, see you then.

Oldest comments (0)