Object and Data Structure Basics

From rbachwiki
Jump to navigation Jump to search

List

mylist= ['string', 1,2,3]
len(mylist) # get length of list
Result 3

Get part of a list (Slicing)

mylist[1:] gets from index one to the end
result 1,2,3

Concatenate list

another_list = [5,6]
newlist = mylist + anohter_list
result ['string', 1,2,3,5,6]

Add an item to the end of a list

newlist.append('hello')

Remove item from list

newlist.pop() # will pop last item
newlist.pop(0) # will pop index item 0

Sort and Reverse

newlist.sort() # sort list in place, which means you have to call newlist again to get the sorted results. you cannot do x = newlist.sort() becasue it will return nothing
numlist.reverse() # reverse in place

Dictionaries

Has key value pairs

mydict = {'key1':'value1', 'key2':'value2'}
mydict[key1]
out: value1
mydict2 = {'k1':123, 'k2':[0,1,2], 'k3':{'insidekey':100}}
mydict2['k2'][2]
mydict2['k3']['insidekey']

Add to dictionary

mydict2['k4'] = 300

List all keys in dictionary

mydict2.keys()

List all values in dictionary

dict2.values()

List both items and keys

dict2.items()

Tuples

Tuples are immutable

t=(1,2,3)
len(t)
t[0]
t.count(1) # will count the amount of time 1 appears
t.index(1) # will return the first index that 1 occurs

Sets

Sets are unordered collections of unique elements, meaning there can only be one representative of the same object

myset = set()
myset.add(1)
mylist = [1,1,1,2,2,3,3]
set(mylist) # will return only the unique values
output {1,2.3}

Back To Top - Category