Friday, December 21, 2018

Python Lists!

Create Python lists, and access elements
friends = ["amy", "david", "stella", "niyu", "vivek", "michael"]
print (friends)
print (friends[0])
print (len(friends) )

for i in range(len(friends)):
    friends[i] += " smith"
print ( friends )

for i in range(len(friends)):
    friends[i] = "none"
print ( friends )
Mixing different data types
mixarray = [ 1, [9,8], (3,4), 'letter', {0:'first'}, 2, 5, 25 ]
mixarray[3]
mixarray[:3]
mixarray[-3:]             # last three elements
mixarray[8:8] = [88,99]   # insert after the last, 
                          # notice mixarray[8] would error out
mixarray[2:5] = [22,55]   # replace the elements,
                          # notice the length does not have to match
# array method: append, remove, extend, pop, sort, index, reversed
a = [2,3,4]
b = ['two','three','four']
h = zip(a, b)
Modify and merge elements in lists
mixarray.append( 'dog' )
print (mixarray)

mixarray.extend( 'cat' )
print (mixarray)

mixarray.extend( [ 'cat' ] )
print (mixarray)

mixarray += 'pig'
print (mixarray)

mixarray += [ 'pig', 'donald duck' ]
print (mixarray)
Slice Strings
filename = r"C:\dir\new"                     
filename = 'C:\\dir\\new'
filename = 'C:/User/myname/dirname'
a = ['amy','smith']
s = ' '.join(a)
s.join(" baz")
n = len(s)
Slice the lists
mixarray[2:3]
print (mixarray[5:])
mixarray[:8]
print (mixarray[4:-1]) 
print (mixarray[-1])

print (mixarray[:]) ## the while array
mixarray[2:4] = ['new1', 'new2'] ##  this replace [2] [3]
print (mixarray)
mixarray[2:3] = ['new3', 'new4'] ##  this replace mixarray[2] with two elements 'new3', 'new4'
print (mixarray)

newary = mixarray[:]             ## copy the whole array
newbry = mixarray[-2:]           ## last 2 elements
newcry = mixarray[::-1]          ## reverse the whole array
s = 'xxyyzzppqqmm'
t = s[slice(None,None,-1)]       ## same as s[::-1]
Insert and remove elements in lists
del mixarray[-2:] ## this delete the last 2 elements
print (mixarray)

mixarray.insert( 2, 'monkey' )
print (mixarray)

del mixarray[2]
mixarray.remove ('donald duck')
print (mixarray)
Looping over the lists
import
for i in mixarray:
    print ( i, end=' ' )
print()
for k,v in enumerate (mixarray):
    print ( k, ':', v, end=' / ' )
print()

from collections import Counter
Counter(mixarray)
# Counter(mixarray) # this will error out
s = "this is a string, a very long string"
Counter(s)
Counter(s[0])
Quick Reference

No comments:

Post a Comment