""" John Rachlin DS 2000: Intro to Programming with Data Filename: list_fundamentals.py Description: The fundamental things everyone needs to know about lists """ #%% Lists are a way of collecting data together under # one variable primes = [2, 3, 5, 7, 11, 13] words = ['to', 'be', 'or', 'not', 'to', 'be'] # Lists can contain one or more data types # There is an implied ordering (position) # STARTING AT ZERO! #%% Indexing lists - fetching a particular value words[0] primes[0] # But watch out! primes[6] #%% Sum simple functions on lists len(primes) sum(primes) min(primes) max(primes) #%% 2+2 #%% Some useful methods on lists primes = [2, 3, 5, 7, 11, 13] primes.append(17) primes.append(19) primes words.sort() primes.sort(reverse=True) words primes #%% Splitting phrase = "Hello! How are you? I am fine! Goodbye" words = phrase.split(" ") words #Example 2 line = "Smith,6175551234,88,3.14\n" vals = line.split(",") vals #%% Negative indexing # First word words[0] # Last word words[-1] # Second word words[1] # Second to the last word words[-2] #%% Testing if something is in a list 2 in primes 4 in primes #%% Initialize an empty list empty = [] len(empty) #%% Initialize 13 counters (0 to 12) outcomes = [0] * 13 outcomes #%% Let's roll some dice import random as rnd import matplotlib.pyplot as plt n = 100000 counter = 0 outcomes = [0] * 13 while counter < n: roll = rnd.randint(1,6) + rnd.randint(1,6) outcomes[roll] += 1 counter += 1 # Barcharts! plt.bar(range(0,13), outcomes) #plt.scatter(range(0,13), outcomes, marker='x')