# Python collections
Published on 25 June 2019

Like every programming language Python basic collections exists of the following types:

List:
Storing unordered a sequence of multiple items of data like strings, integers etc.

#Initialization
my_list = [123, 'abc', 'hello']

#Add an item
my_list.append('world')

#Print the list contents
print(my_list)
#[123, 'abc', 'hello', 'world']

#Print the second one
print(my_list[1])
#abc

#Reassign the second
my_list[1] = 'Foo'

#Print the list contents
print(my_list)
#[123, 'Foo', 'hello', 'world']

#Print the size
print(len(mylist))
#4

#Get the index of an item
mylist.index('hello')
#2

 

Dictionary
Storing an unordered sequence of key value pairs

#Initialization
my_dict = {'a': 344, 34:'Foo', 'b': 'Bar'}

#Get the entry with key 'b'
my_dict.get('b')
#Bar

#Add or update the entry with key 'b'
my_dict.update({'b': 123})

#Print contents
print(my_dict)
#{'a': 344, 34: 'Foo', 'b': 123}

 

Tuple
An immutable unordered sequence of items

#Initialization
my_tuple = (1, 222, 1, 'hello', 'world', 'hello', 'hello')

#Get the number of occurence of item 'hello'
my_tuple.count('hello')
#3

#Get the index of the first occurence of 'hello'
my_tuple.index('hello')
#3

 

Set
An immutable unordered unique sequence of items

#Initialization
my_set = set()

#Add items
my_set.add(1)
my_set.add(222)
my_set.add('Hello')
my_set.add('Hello')
my_set.add('Hello')

#Print contents
print(my_set)
#{1, 222, 'Hello'}

#Add a sequence
my_set.update([5, 'Wow'])

#Print contents
print(my_set)
#{1, 222, 5, 'Hello', 'Wow'}

#Remove item
my_set.remove('Hello')

#Print contents
print(my_set)
#{1, 222, 5, 'Wow'}