Written as a list of comma-separated values (items) between square brackets ([ ])
Items in a list need not be of the same type
sample_list = [] # declaring a list
sample_list = [1,2,3] # same type values in list
sample_list = [1, 'mixed', True] # mixed list
sample_list = [1, 'mixed', True, [1, False], {'dictionary': 'this is an example'}]
# even other object types like tuple, list, dictionary or even function,
# class instance etc can also be stored within a list
Access an element of a list
sample_list = [1, 'mixed', True, [1, False]]
# can access the content using index, index starts from 0
sample[2] # it gives True
sample[-2] # it also gives True (2nd element from the end)
modifying elements of the list
sample_list = [1, 'mixed', True, [1, False]]
sample_list[2] = 5 # it replaces True with 5
Operations on the list:
sample_list = [1, 'mixed', True, [1, False]]
# input for all operation remains this sample_list, irrespective of prev operations
# length (gives number of elements in the list)
len(sample_list) # gives 4 as the value, since 4 elements in the list
# append (add elements to the list)
sample_list.append([5]) # it gives [1, 'mixed', True, [1, False], 5]
# extend (add concatenate two lists)
sample_list.extend([5]) # it gives [1, 'mixed', True, [1, False], 5]
sample_list + [5] # it also gives [1, 'mixed', True, [1, False], 5]
# slicing, includes 1st index excludes 3rd index in example
sample_list[1:3] # then we get 1 and 2 index item ['mixed', True]
sample_list[1:-1] # -1 corresponds to end, gives [1, 'mixed', True]
sample_list[2:] # gives all elements from 2nd index till end
# reversing
sample_list[::-1]
# not spacifying first and second value between : gives all elements
# that is we are not selecting index and choosing all, -1 indicates reverse
# other slicing operations
test_list = [1,2,3,4,5,6,7,8,9]
test_list[::3] #[start:end:steps], skips every 2 elements, [1,4,6,9]
test_list[:6:2] # print till 6th index, skips every alternate elements, [1,3,5]
# deletion
# membership
'mixed' in sample_list # print True
False in sample_list # prints False (since False is not direct element of list)
# max, returns the maximum value
max(sample_list) # it will throw an error, all elements should be of same type
max(['mixed','sample','ankit']) # will return 'sample'
# min, again all elements should be of same type for comparison
min(['mixed','sample','ankit']) # will return 'ankit'
# sort, again all elements should be of same type for comparison
a = ['mixed','sample','ankit']
a.sort() # now a is a sorted array with a = ['ankit', 'mixed', 'sample']
# repetition
a = [4,5]*4 # then a = [4, 5, 4, 5, 4, 5, 4, 5]
Tuple
A tuple is a collection of objects which ordered and immutable
tup1 = ('a', 'b', 3, 6, 53, 4) # comma separated in (), is the way to define tuple
tup2 = 'a', # putting simply comma also gives a tuple
tup3 = (5) # this is not a tuple, comma is must for it to be a typle
print(tup1[0]) # accessing an element using index is possible for tuple
print(tup1[1:4]) #slicing just like list is also possible
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
tup1.extend(tup2) # not possible, throws an error since modification not allowed
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
Since tuple can not be changed; append, extend, reversing, deletion, insert, sort, and other operations, similar to lists, which modifies the given tuple are not possible.
Re-assignment is possible though
Iteration, membership, iteration, length, min, max, and other operations are possible for tuple
We can typecast a list into a tuple as well
Range
Generally used for loop
range(3, 21, 2) # raed it like range(start:end:step), end is not inclusive
# it will generate 3,5,7,9,11,13,15,17,19
Set
Sets use parentheses {}
Can have any number of elements, and any type of element except mutable one
A set cannot have mutable elements like lists, sets, or dictionaries as its elements
Have only unique values, no duplicates allowed
set is unordered (order is not important and is not preserved), hence indexing is not important
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
# set cannot have duplicates
my_set = {1, 2, 3, 4, 3, 2} # Output: {1, 2, 3, 4}
# we can make set from a list
my_set = set([1, 2, 3, 2]) # Output: {1, 2, 3}
# set cannot have mutable items
# here [3, 4] is a mutable list
my_set = {1, 2, [3, 4]} # this will cause an error
Set operations such as union, intersection, and difference are also possible
# & (and) gives intersection
{1,4,6,2} & {2,6,3,9} # it gives {2, 6}
# | (or) gives union
{1,4,6,2} | {2,6,3,9} # output is {1, 2, 3, 4, 6, 9}
# - (minus) gives the difference
{1,4,6,2} - {2,6,3,9} # output is {1, 4}
Mapping
Dictionary
A dictionary is made up of different keys and values
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces
keys can not be a duplicate in a dictionary
Keys are not ordered in the dictionary (this is an important point to note)
dictionary2 = {}
dictionary2['First Person'] = {}
dictionary2['First Person']["Name"] = "Ankit"
dictionary2['First Person']["Surname"] = "Choudhary"
dictionary2['Second Person'] = {"Name": "Amar", "Surname": "Singh"}
dictionary2['Third Person'] = {"Name": "MS", "Surname": "Dhoni"}
'''The entity dictionary2 can be created in multiple ways as presented above
The outcome is same for all. The final identiy looks like
dictionary2 = {"First Person" : {"Name": "Ankit", "Surname": "Choudhary"},
"Second Person" : {"Name": "Amar", "Surname": "Singh"}}
"Third Person" : {"Name": "MS", "Surname": "Dhoni"}
'''
Accessing Values in Dictionary
print(dictionary2['First Name']['Name']) # it will print "Ankit"
print(dictionary2['Second Name']['Name']) # it will print "Amar"
print(dictionary2['Fourth Name']['Name']) # throws an error
# if key is not present, throws an error
print(dictionary2.get('Fourth Name')
# it will print None, because key is not present, get avoid getting an error
print(dictionary2.get('Fourth Name', {'Name':'Not found', 'Surname': 'Not Found'})
# prints the assigned default value, when key is not found
print(len(dictionary2)) # returns number of keys in the dictionary (top level keys)
Listing all keys (first level) in a dictionary
# Taking dictionary2 for the example:
list(dictionary2.keys()) # will give: ["First Name", "Second Name", "Third Name"]
dictionary2['First Name'].keys() # will give: dict("Name", "Surname")
# Using for loop, we can loop over, and access all the values for the dictionary