Categories
Blog Data Science Python

Python random numbers

When I experiment in Python I often need a list of random integers. When I was looking for code to generate that I couldn’t believe how complicated people are doing that and present it after in their blog. Anyway here are two very easy ways to generate random lists.

import random
[random.randint(1,100) for i in range(10)]
#
import numpy as np
np.random.randint(1,100,10)
 

Categories
Blog Data Science Python

Python Tuples

Tuples are immutable sequences typically used to store heterogeneous data. They are similar to Lists but aren’t the same. In this post, I wanna give you a quick intro in Tuples by explaining the differences to Lists.

myList = [1,2,3]

myTuple = (1,2,3)
 

As you can see instead of square brackets [ ] we use parentheses ( ) to create a Tuple.

myList == myTuple # = False

Out[3]: False

myList[2] = 4

myTuple [2] = 4

Traceback (most recent call last):

File "", line 1, in 

    myTuple [2] = 4

TypeError: 'tuple' object does not support item assignment

myTuple = (1,4,3)
 

Although our List and Tuple have the same content, we can’t compare these two objects. Another insight is that values in a List are mutable whereas the values of a Tuple are immutable. To replace a value you have to redefine the Tuple.

Pack and unpack a Tuple

From edX.org Using Python for Research

x = 12.23

y = 23.34

coordinate = (x,y)

coordinate

Out[8]: (12.23, 23.34)

(c1, c2) = coordinate

c1

Out[10]: 12.23

c2

Out[11]: 23.34

As you can see, Tuples can be useful if you save something meaningful and consistent which you want to protect like coordinates. Another benefit is that Tuples are faster than Lists. Especially when you want to iterate through it, use a Tuple instead of a List. (Sorry WordPress Gutenberg is not a big friend of programmers).