Python
Python
PYTHON
Programming
To create a list all you have to do is to place the items inside a square bracket [] separated by comma ,.
Examples:
# list of floats
num_list = [11.22, 9.9, 78.34, 12.0]
# list of int, float and strings
mix_list = [1.13, 2, 5, "beginnersbook", 100, "hi"]
# an empty list
nodata_list = []
Accessing the items of a list
Syntax 2. The index must be in range to avoid IndexError. The
◦ list_name[index] range of the index of a list having 10 elements is 0 to 9,
A tuple is similar to List except that the objects in tuple are # tuple of strings
immutable which means we cannot change the elements of my_data = ("hi", "hello", "bye")
a tuple once assigned. print(my_data)
◦ Dictionary is a collection of key and value pairs. A dictionary doesn’t allow duplicate keys but the values can be duplicate. It
is an ordered, indexed and mutable collection of elements. Dictionary is a mutable data type in Python. A python dictionary is
a collection of key and value pairs separated by a colon (:), enclosed in curly braces {}.
◦ Example:
◦ mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
Accessing dictionary values using keys in Python
◦ To access a value we can can use the corresponding key in the square brackets as shown in the following example. Dictionary
name followed by square brackets and in the brackets we specify the key for which we want the value.
◦ mydict['StuAge'] = 31
◦ mydict['StuCity'] = 'Noida‘
◦ We can also add a new key-value pair in an existing dictionary. Lets take an example to understand this.
◦ mydict['StuClass'] = 'Jr.KG'
◦ A set is an unordered and unindexed collection of items. This means when we print the elements of a set they will appear in
the random order and we cannot access the elements of set based on indexes because it is unindexed.
◦ Elements of set are separated by commas and enclosed in curly braces
◦ Set is an unordered and unindexed collection of items in Python. Unordered means when we display the elements of a set, it
will come out in a random order. Unindexed means, we cannot access the elements of a set using the indexes like we can do
in list and tuples.
◦ Example
◦ # Set Example
◦ print(myset)
◦ Checking whether an item is in the set
◦ We can check whether an item exists in Set or not using “in” operator as shown in the following example. This
returns the boolean value true or false. If the item is in the given set then it returns true, else it returns false.
◦ # Set Example
◦ myset = {"hi", 2, "bye", "Hello World"}
◦ # checking whether 2 is in myset
◦ print(2 in myset)
◦ # checking whether "hi" is in myset
◦ print("hi" in myset)
◦ # checking whether "BeginnersBook" is in myset
◦ print("BeginnersBook" in myset)