When to use list vs. tuple vs. dictionary vs. set?

Answer Posted / chaitanya

List is like array, it can be used to store homogeneous as well as heterogeneous data type (It can store same data type as well as different data type). List are faster compared to array. Individual element of List data can be accessed using indexing & can be manipulated.

List Code Snippet:

list = ["Sarah",29,30000.00]

for i in range (3):

print list[i]

------------------

Output

Sarah

29

30000.0

Tuples are similar to lists, but there data can be changed once created throught the execution of program. Individual element of Tuples can be accessed using indexing.

Tuples Code Snippet: The Days

days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")

print days

------------------------------

('Sunday', 'Mondays', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')

Sets stores unordered values & have no index. And unlike Tuples and Lists, Sets can have no duplicate data, It is similar to Mathematical sets.

add() function can be used to add element to a set.

update() function can be used to add a group of elements to a set.

Copy() function can be used to create clone of set.

Set Code Snippet:

disneyLand = set (['Minnie Mouse', 'Donald Duck', 'Daisy Duck', 'Goofy'])

disneyLand.add('Pluto')

print disneyLand

-----------------------------------------------

Output

set(['Goofy', 'Daisy Duck', 'Donald Duck', 'Minnie Mouse', ’Pluto’])

Dictionary are similar to what their name is. In a dictionary, In python, the word is called a 'key', and the definition a 'value'. Dictionaries consist of pairs of keys and their corresponding values.

Dictionary Code Snippet:

>>> dict = {'India': 'Bharat', 'Angel': ‘Mother Teresa’, 'Cartoon': 'Mickey'}

>>>print dict[India]

Bharat

>>>print dict[Angel]

Mother Teresa

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Is it easy to learn python?

431


What are python methods?

450


Write code to print everything in the string except the spaces.

482


What is the difference between remove() function and del statement?

464


What is python constructor?

490






How do you iterate over a list and pull element indices at the same time?

658


What is the python keyword "with" used for?

496


What are pytest fixtures?

474


Can we change tuple values? If yes, give an example.

534


Explain how you can minimize the memcached server outages in your python development?

514


What is numpy? Is it better than a list?

501


What is the statement that can be used in Python if a statement is required syntactically but the program requires no action?

543


What is the language from which Python has got its features or derived its features?

528


Does python require coding?

443


Explain tkinter in python

471