Question:

For python users (programming)?

by  |  earlier

0 LIKES UnLike

2 questions id like to ask

What is the difference between a tuple and a list?

What is the difference between a list and a dictionary?

 Tags:

   Report

2 ANSWERS


  1. As far as I know:

    You can't modify tuple but you can modify list. This is should be more memory efficient.

    List contains just variables that have position in that list (lis[0], lis[-1] ..) but in dictionary you don't have clear position for all variables but you can use other variables as keys ("bookmarks") for your variables. So you create a simple phonebook using:

    phonebook = {'Mike':12345, 'Keke':98765, 'Mother': 98123}

    now you can fetch Mikes number using phonebook['Mike']

    Of course you can use other variables than strings as your keys:

    tuple1= ('Dipum', 'Dipam', 'piupou')

    tuple2 = ('Pitim', 'Pitam')

    dictionary1 = {tuple1:'todii', tuple2:1233, 'magic':tuple1}

    dictionary1[tuple1]

    dictionary1[dictionary1['magic']]

    If you think about it, there is clear reason why you can use tuples as keys but you can't use lists.


  2. A tuple is not modified once created ; if you have a C programming background, then you can think of a tuple as an array of constant ; while a list is modifiable so it can be assigned new elements ot get its elements deleted .

    Many functions return tuples as a return value , so that the caller for these functions wouldn't modify the result .

    A list is just analogous to an array : It's indexes are numeric ( 0,1,2, ...).

    You can think of a dictionary as a list whose indexes can be anything non numerical as long as these indexes are unmodifiable ( strings, tuples, numbers )

    BTW, I answered ur other question regarding the countLines(), but seems that Yahoo Answers doesn't retain the indentation , which is essential for Python. So I am sending the same source BUT substitute EACH occurrence of the '@' symbol below with a space  so that you get the correct logical indentation for the program to run :P

    import sys # for exit()

    def countLines() :

    @n=0 # to hold the number of lines

    @try :

    @@f = open ("somefile.txt") // use correct file name and path

    @@for line in f :

    @@@n = n +1

    @@return n

    @except :

    @@print "File error. The program will end "

    @@sys.exit()

    numberofLines = countLines()

    print 'The file ',numberofLines,'lines'

    raw_input()

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.