Python - Lists, dictionaries and tuples
A quick overview over lists, dictionaries and tuples.
Literal notation (empty)
list = []
dict = {}
tuple = ()
Literal notation (one or more elements)
list = [1]
list = [1,2,3]
dict = {"key1": value1}
dict = {"key1": value1, "key2": value2}
tuple = 1, # equal to tuple = (1,)
Lists usage overview
li = [1,2,3]
print li[0] # 1 - first
print li[0:2] # [1, 2]
print li[:2] # [1, 2]
print li[-1] # 3 - last
len(li) # 3 - returns length
li.extend([4,5]) # [1,2,3,4,5] - adds items
li.append([6,7]) # [1,2,3,4,5, [6,7] ] - adds list of items
li.remove(2) # [1,3,4,5, [6,7] ]
li.pop() # [1,3,4,5] - removes the last (stack)
li.pop(0) # [3,4,5] - removes the first (queue)
li = li + [8,9] # [3,4,5,8,9]
li = li + [10] * 2 # [3,4,5,8,9,10,10]
li.index(5) # 2 - position of item 5 (starting from zero)
1 in li # True
Dictionaries usage overview
dic = { “server”: “a”, “database” : “db” }
print dic[“server”] # “a”
dic[“server”] = “b” # { “server”: “b”, “database” : “db” }
del dic[“server”] # { “database” : “db” }
dic.clear() # {}
Tuples usage overview
Tuples don't have access to extend
, append
, remove
or pop
but we can add items with concatenation +
or change its contents.
tuple = (1,2,3)
print tuple[0] # 1 - first
print tuple[0:2] # (1, 2)
print tuple[:2] # (1, 2)
print tuple[-1] # 3 - last
print len(tuple) # 3 - returns length
tuple = tuple + (8,9) # (1,3,4,5,8,9)
tuple = tuple + (10,) * 2 # (1,3,4,5,8,9,10,10)
print tuple.index(4) # 2 - position of item 4 (starting from zero)
print 1 in tuple # True
##changing the content of a tuple
another_tuple = [],
another_tuple[0].extend( [1,2,3] ) # ( [1,2,3], )
another_tuple[0].pop() # ( [1,2], )
another_tuple[0].clear() # ( [], )
Written by gerardsans
Related protips
2 Responses
what about li.pop(0) ? ;)
over 1 year ago
·
Thanks! Included now.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#