Difference between revisions of "Object and Data Structure Basics"

From rbachwiki
Jump to navigation Jump to search
Line 3: Line 3:
  len(mylist) # get length of list
  len(mylist) # get length of list
  Result 3
  Result 3
Get part of a list (Slicing)
'''Get part of a list (Slicing)'''
  mylist[1:] gets from index one to the end
  mylist[1:] gets from index one to the end
  result 1,2,3
  result 1,2,3
Concatenate list
'''Concatenate list'''
  another_list = [5,6]
  another_list = [5,6]
  newlist = mylist + anohter_list
  newlist = mylist + anohter_list
  result ['string', 1,2,3,5,6]
  result ['string', 1,2,3,5,6]
Add an item to the end of a list
'''Add an item to the end of a list'''
  newlist.append('hello')
  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

Revision as of 21:29, 2 January 2019

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