Press "Enter" to skip to content

Python Notes 3 : Lists, Dictionaries & Tuples

In the following & subsequent notes, we will talk about a few well known data structures in practice.

Lists

  • A single list can hold multiple object types at the same time
    • my_list = [‘A string’, 23, 100.232,’O’]
  • Basic operations available are
    • new_list.sort()
    • new_list.append(‘XYZ’)
    • new_list.reverse()
    • new_list.pop(0)
      • Above statement returns the element at position 0 & removes it from the list as well
      • By default, pop() function will return the last element in the list
  • We can create nested lists
    • list_1 = [1,2,3]
    • list_2 = [4,5,6]
    • list_3 = [7,8,9]
    • my_list = [list_1,list_2,list_3]
    • my_list[0]
      • O/P -> [1,2,3]
    • my_list[0][0]
      • O/P -> 1

Dictionaries

  • This data structure in python is analogous to hash tables in other languages
  • Values are stored in this data structure as key,value pair
    • my_dict = {‘key1′:’value1’ , ‘key2′:’value2’}
  • Nesting with Dictionaries
    • d = {‘key1’:{‘nestkey’:{‘subnestkey’:’value’}}}
    • d[‘key1’][‘nestkey’][‘subnestkey’]
      • O/P -> ‘value’
  • Basic Operations
    • d = {‘key1’:1, ‘key2′:2,’key3’:3}
    •  d.keys()
      • Method returns a list of all keys
        • O/P -> [‘key3′,’key2′,’key1’]
    • d.values()
      • Method to grab all the values
        • O/P -> [3,2,1]

Tuples

  • Tuples are immutable lists. If in your program you are passing around an object and need to make sure it doesn’t gets changed, this data structure is the right option for you
  • They are used to represent something which shouldn’t be changed e.g. days of the week, dates, calendar etc
  • Syntax –
    • t = (1,2,’three’)
  • Basic Operations available are –
    • Use .index to enter a value and return the index
      • t.index(‘three’)
        • O/P -> 2
    • Use .count to count the number of times a value appears
      • t.count(‘three’)
        • O/P -> 1
  • Since tuples are immutable lists, we cannot add/amend it once they get created
    • t.append(‘Not Allowed’) will simply won’t work
    • t[0]=’XYZ’ won’t work

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *