Sunteți pe pagina 1din 25

COMBINED DATA TYPE

List
Tuple

Dictionary
Set
LIST
• The simplest data structure in Python and is used to store a list of values.
• Lists are collections of items (strings, integers, or even other lists).
• Each item in the list has an assigned index value.
• Lists are enclosed in [ ]
• Each item in a list is separated by a comma
• Unlike strings, lists are mutable, which means they can be changed.
LIST
L=["Python", "C", "C++", "Java", "Scala"]
L[0] L[1] L[2] L[3] L[4]
"Python" "C" "C++" "Java" "Scala"
L[-5] L[-4] L[-3] L[-2] L[-1]
LIST
Function Description
cmp(list1, list2) Compares elements of both lists.
len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
min(list) Returns item from the list with min value.
list(seq) Converts a tuple into list.
Tips: In Python3, the function cmp() has been taken place by operator.
LIST

list.append(obj) Appends object obj to list


Returns count of how many times obj occurs in
list.count(obj)
list
Appends the contents of seq to list (Same as +=
list.extend(seq)

list.index(obj) Returns the lowest index in list that obj appears
list.insert(index, obj) Inserts object obj into list at offset index
list.pop(obj=list[-1]) Removes and returns last object or obj from list
list.remove(obj) Removes object obj from list
list.reverse() Reverses objects of list in place
list.sort([func]) Sorts objects of list, use compare func if given
LIST
Generate List with Expression

[expression for item in iterable]


[expression for item in iterable if condition]

Example:
leaps = [ y for y in range(1900, 1940) if (y%4 ==0 and y%100!=0) or (y%400 == 0)]
TUPLE
• A tuple is a sequence of immutable Python objects.
• Tuples are sequences, just like lists.
• The differences between tuples and lists are, the tuples cannot be changed unlike lists and
tuples use parentheses, whereas lists use square brackets.
TUPLE
There are only two functions for tuple (Assume a tuple named t)
t.count(x) ---- Return count of element x
t.index(x) ---- Return the index of element x

And also +, * and index [] are available

The Following table is the index sequence:


L = "python", "java", "C", "C++"
L[0] L[1] L[2] L[3]
"Python" "Java" "C" "C++"
L[-4] L[-3] L[-2] L[-1]
TUPLE
L[0] L[1] L[2] L[3]
"Python" "Java" "C" "C++"
L[-4] L[-3] L[-2] L[-1]
TUPLE
Tips:
Some style established by usage
We will not use round brakets “()” in the following case:
1. Tuples appear to the left of the binary operator.
a, b = (1, 2)
for x, y in ((1,2), (3, 4)):
print(x,y)
2. When a tuple appears to the right of the unary operator.
del a, b
def f(x):
return x, x**2
SET
What is set ?
A set is a collection of unique elements which is unordered and unindexed.

How to generate set ?


1. set() can be used to create a new empty set.
2. New_set = { ‘a’, ‘b’, 1, 2 }
3. If a list or string contains only object with hash function, then we can convert it to set.
SET
Operation Equivalent Result
len(s) number of elements in set s (cardinality)
x in s test x for membership in s
x not in s test x for non-membership in s
s.issubset(t) s <= t test whether every element in s is in t
s.issuperset(t) s >= t test whether every element in t is in s
s.union(t) s|t new set with elements from both s and t
s.intersection(t) s&t new set with elements common to s and t
s.difference(t) s-t new set with elements in s but not in t
s.symmetric_difference(t) s ^ t new set with elements in either s or t but not both
s.copy() new set with a shallow copy of s
SET
Operation Equivalent Result
s.update(t) s |= t return set s with elements added from t
s.intersection_update(t) s &= t return set s keeping only elements also found in t
s.difference_update(t) s -= t return set s after removing elements found in t
s.symmetric_difference_update(t) s ^= t return set s with elements from s or t but not both
s.add(x) add element x to set s
s.remove(x) remove x from set s; raises KeyError if not present
s.discard(x) removes x from set s if present
s.pop() remove and return an arbitrary element from s;
raises KeyError if empty
s.clear() remove all elements from set s
SET
frozenset is just an immutable version of a Python set object. While elements of a set can be modified
at any time, elements of frozenset remains the same after creation.
Due to this, frozensets can be used as key in Dictionary or as element of another set. But like sets, it
is not ordered (the elements can be set at any index).

frozenset Functions:
frozenset.copy()
frozenset.difference()
frozenset.intersection()
frozenset.isdisjoint()
frozenset.issubset()
frozenset.isupperset()
frozenset.union()
frozenset.symmetric_difference()
SET

When binary operations are applied with set and frozenset, the data type of the result is the
same as the data type of the left operand

The comparison operator does not matter if both sets contain the same item
>>> commonset=set("apple")
>>> frozenset_1=frozenset("apple")
>>> commonset == frozenset_1
True
MAPPING TYPE
A mapping object maps values of one type (the key type) to arbitrary objects. Mappings are mutable
objects. There is currently only one mapping type, the dictionary. A dictionary's keys are almost
arbitrary values. The only types of values not acceptable as keys are values containing lists or
dictionaries or other mutable types that are compared by value rather than by object identity.

Numeric types used for keys obey the normal rules for numeric comparison: if two numbers
compare equal (e.g. 1 and 1.0) then they can be used interchangeably to index the same dictionary
entry.
DICT
1. How to create dictionary ?
a) Create an empty dict:
dict_empty = {}
b) Assign contents directly:
dic = {‘python':1, ‘Java':2, ‘C':3}
c) With dict function:
dic = dict(python = 1, Java = 2, C =3)
d) With Binary group list:
list_dic = [('python', 1), ('Java', 2), ('C', 3)]
dic = dict(list_dic)
e) dict & zip
dic = dict(zip('abc', [1, 2, 3]))
f) Expression
dic = {i:2*i for i in range(3)}
g) dict.fromkeys()
dic = dict.fromkeys(range(3), 'x')
21
blue
‘venus’
[75, “R”, 2]
-14
(4,11)
None
18

>>> d = {(4,11):18, "blue":[75,"R", 2], -14:None, 21:'venus'}


>>> d[(4,11)]
18
>>> d["blue"]
[75, 'R', 2]
>>> d[-14]
>>> d[25] #Nonexistent key will cause KeyError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 25
DICT
Operations of dict d:

len(d) the number of items in d

d[k] return the value of key k

d[k] = v set d[k] to v

del d[k] delete d[k] from dictionary d

k in d equivalent to d.has_key(k) (has_key only works in Python 2.7.X)

k not in d return true if k is not a key of d


Function Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
Remove the item with key and return its value or d if key is not found. If d is not provided
pop(key[,d])
and key is not found, raises KeyError.
Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is
popitem()
empty.
If key is in the dictionary, return its value. If not, insert key with a value of d and return d
setdefault(key[,d])
(defaults to None).
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys.
values() Return a new view of the dictionary's values
has_key() Check if the dict has a certern key
DICT
Iteration: For dictionary contains both key and values, we can process the
iteration base on (key, value), key or value. Iteration methods as following:
(key, value):
for item in d.items(): for key, value in d.items():
print(item[0], item[1]) print(key, value)
key:
for key in d: for key in d.keys():
print(key, d[key]) print(key, d[key])
value:
for value in d.values():
print(value)
DICT
dict.items(), dict.keys(), and dict.values() return the dictionary view. The
dictionary view is a read-only iterable object. When the dictionary changed,
the dictionary view will change. And we can proceed some operations like
set between key view and item view(&, |, -, ^).
d = {}.fromkeys("abcd",0) #{'a': 0, 'b': 0, 'c': 0, 'd': 0}
s = set("abs") #{'a', 'b', 's'}
inner = d.keys() & s #{'a', 'b'}
DICT
Defaultdicts: defaultdict is a subclass of dict. In defaultdict, the KeyError will
never happen. When we run value = d[25], it will create a key 25(not exist)
and assign a default value.

Input:
import collections
d=collections.defaultdict(int)
x=d[25]
d.keys(), x
Output:
(dict_keys([25]), 0)

S-ar putea să vă placă și