Compound data types in Python

This blog explains about compound data types in Python.

Compound Data Types:

 * List

Dictionaries

Tuples

Sets

List:

A list is an array of objects. An object can be an integer,a string,float or other things.

Example:

mylist = [“John”, “Smith, 29]

PYTHON LIST PROPERTIES

  • Lists are ordered.
  • Lists can contain any arbitrary objects.
  • List elements can be accessed by index.
  • Lists can be nested to arbitrary depth.
  • Lists are mutable.
  • Lists are dynamic.

Dictionaries:

Sometimes, dictionaries are a better choice to store data. For example, in the example where the user would enter their name, surname and age a dictionary would be a better choice to store the data:

mydict = {“name”:”John”, “surname”:”Smith”, “age”:29}

Tuples:

Tuples are just like lists but they are immutable. Once you define a list you can add new items to them,remove existing items and so on. But you cannot do that with a tuple.

mytuple = (10, 20, 30)

The difference with lists in terms of syntax is that tuples are written with round brackets. Indexing works the same with lists.

Sets:

Sets like dictionaries in that they don’t keep record of the order or their items. They also don’t accept to have duplicate values.

myset={10,20,30}

Sets are sometimes useful to remove duplicates from lists. Example:

mylist = [10, 11, 11]

myset = set(mylist)

mylist = list(myset)

print(mylist)

So, what we did there was we used the set() function to convert mylist into a set. That will create a set with items 10 and 11 only. Then we use the list() function to convert that set back to a list. So, we get [10, 11] as output.