Data Structures in Python
Data Structures in Python
Lists
Dictionary
Tuples
Sets
LISTS
List is most versatile datatype available in Python, written as a list of comma-
separated values (items) between square brackets.
Items in a list can be Heterogenous types(need not be of the same type).
Lists are mutable
Concatenation produces a new lists.
Append function extends a list with a new value without changing it.
LISTS ARE MUTABLE
A mutable object can be changed after it's created, and an immutable object
cannot be changed after its created.
list. extend ( L): Extend the list by appending all the items in the given list.
list. clear ( ): Remove all items from the list. Equivalent to del a[:] .
Not supported in python 2.X.
list.reverse(): Reverse a given list.
list. index ( x): Return the index in the list of the first item whose value is x. It is an
error if there is no such item.
list. count ( x): Return the number of times x appears in the list.
To retrieve an item from the top of the stack, use pop() without an explicit index.
Example:
USING LISTS AS QUEUES
Python also uses a list as a queue where the first element added is the first element
retrieved.
Lists are not efficient when used as a queue.
While appends and pops from the end of list are fast, doing inserts or pops from the
beginning of a list is slow.
To implement a queue, use collections.deque which was designed to have fast
appends and pops from both ends.
Example:
List Comprehensions
List comprehensions is very similar to set theory or set builder form .
List comprehensions provide a concise way to create a lists.
Allows to build a new set from existing sets.
Is an extension to the lists.
Examples:
Create a list of two tuples using list comprehension
Set difference: In this, elements present in set2 is not included in the resultant set.
It can be don using “set1-set2