<jupyter_start><jupyter_text>List And Dictionaries  LIST<jupyter_code>from IPython.display import Image
Image('images/lists.jpeg')<jupyter_output><empty_output><jupyter_text>How to create a list?<jupyter_code># empty list
my_list = []
print(my_list)
from IPython.display import Image
Image('images/empty list.png')
# list of integers
my_list = [1, 2, 3]
print(my_list)
# Adding the values irrespective of their data type: Integer, String, float.
my_list = [1, 2, 3, 'Tanu', 4.0, 4/2]
print(my_list)<jupyter_output>[1, 2, 3, 'Tanu', 4.0, 2.0]<jupyter_text>A list can also have another list as an item. This is called a nested list.<jupyter_code># nested list
my_list = ["mouse", [8, 4, 6], ['a']]
print(my_list)
print(type(my_list))<jupyter_output><class 'list'><jupyter_text>How to access elements from a list? There are various ways in which we can access the elements of a list.  List index<jupyter_code>from IPython.display import Image
Image('images/index list.jpg')<jupyter_output><empty_output><jupyter_text>We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.Trying to access indexes other than these will raise an IndexError. The index must be an integer. We can't use float or other types, this will result in TypeError.<jupyter_code># List indexing

my_list = ['p', 'r', 'o', 'b', 'e']

# Output: p
print(my_list[0])

# Output: o
print(my_list[2])

# Output: e
print(my_list[4])

from IPython.display import Image
Image('images/nested list.jpg')<jupyter_output><empty_output><jupyter_text>Nested lists are accessed using nested indexing.<jupyter_code># Nested List
n_list = ["Happy", [2, 0, 1, 5]]

# Nested indexing
print(n_list[0][1])

print(n_list[1][3])
# Error! Only integer can be used for indexing
print(my_list[4.0])<jupyter_output><empty_output><jupyter_text>Negative indexing<jupyter_code># Negative indexing in lists
my_list = ['p','r','o','b','e']

print(my_list[-1])

print(my_list[-5])
from IPython.display import Image
Image('images/python-list-index.png')<jupyter_output><empty_output><jupyter_text>How to slice lists in Python? We can access a range of items in a list by using the slicing operator :(colon).<jupyter_code># List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# elements 3rd to 5th
print(my_list[2:5])

# elements beginning to 4th
print(my_list[:-5])

# elements 6th to end
print(my_list[5:])

# elements beginning to end
print(my_list[:])
from IPython.display import Image
Image('images/element-slicing.jpg')<jupyter_output><empty_output><jupyter_text>How to change or add elements to a list?<jupyter_code># Correcting mistake values in a list
odd = [2, 4, 6, 8]

# change the 1st item    
odd[0] = 1            

print(odd)

# change 2nd to 4th items
odd[1:4] = [3, 5, 7]  

print(odd)<jupyter_output>[1, 4, 6, 8]
[1, 3, 5, 7]<jupyter_text>We can add one item to a list using the append() method or add several items using extend() method.<jupyter_code>from IPython.display import Image
Image('images/list append.png')
# Appending and Extending lists in Python
odd = [1, 3, 5]

odd.append(7)

print(odd)
odd.extend([9, 11, 13])

print(odd)<jupyter_output>[1, 3, 5, 7, 9, 11, 13]<jupyter_text>We can also use + operator to combine two lists. This is also called concatenation.The * operator repeats a list for the given number of times<jupyter_code># Concatenating and repeating lists
odd = [1, 3, 5]

print(odd + [9, 7, 5])
print(["re"] * 3)<jupyter_output>['re', 're', 're']<jupyter_text>Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.<jupyter_code># Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)

print(odd)
odd[2:2] = [5, 7]

print(odd)<jupyter_output>[1, 3, 5, 7, 9]<jupyter_text>How to delete or remove elements from a list?<jupyter_code># Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# delete one item
del my_list[2]

print(my_list)
# delete multiple items
del my_list[1:5]

print(my_list)
# delete entire list
del my_list
# Error: List not defined
print(my_list)<jupyter_output><empty_output><jupyter_text>We can use remove() method to remove the given item or pop() method to remove an item at the given index.<jupyter_code>my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

print(my_list)<jupyter_output>['r', 'o', 'b', 'l', 'e', 'm']<jupyter_text>The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure).<jupyter_code>print(my_list.pop(1))
print(my_list)
print(my_list.pop())
print(my_list)<jupyter_output>['r', 'b', 'l', 'e']<jupyter_text>We can also use the clear() method to empty a list.<jupyter_code>my_list.clear()

print(my_list)<jupyter_output>[]<jupyter_text>Python List Methods Methods that are available with list objects in Python programming are tabulated below. They are accessed as list.method(). Some of the methods have already been used above. Python List Methodsappend() - Add an element to the end of the listextend() - Add all elements of a list to the another listinsert() - Insert an item at the defined indexremove() - Removes an item from the listpop() - Removes and returns an element at the given indexclear() - Removes all items from the listindex() - Returns the index of the first matched itemcount() - Returns the count of the number of items passed as an argumentsort() - Sort items in a list in ascending orderreverse() - Reverse the order of items in the listcopy() - Returns a shallow copy of the list<jupyter_code># Python list methods
my_list = [3, 8, 1, 6, 0, 8, 4]
print(my_list)<jupyter_output>[3, 8, 1, 6, 0, 8, 4]<jupyter_text>index() - Returns the index of the first matched item<jupyter_code>print(my_list.index(8))<jupyter_output>1<jupyter_text>count() - Returns the count of the number of items passed as an argument<jupyter_code>print(my_list.count(8))<jupyter_output>2<jupyter_text>sort() - Sort items in a list in ascending order<jupyter_code>my_list.sort()
print(my_list)<jupyter_output>[0, 1, 3, 4, 6, 8, 8]<jupyter_text>reverse() - Reverse the order of items in the list<jupyter_code>my_list.reverse()
print(my_list)<jupyter_output>[8, 8, 6, 4, 3, 1, 0]<jupyter_text>Other List Operations in Python  List Membership Test We can test if an item exists in a list or not, using the keyword in.<jupyter_code>my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

print('p' in my_list)
print('a' in my_list)
print('c' not in my_list)<jupyter_output>True<jupyter_text>Iterating Through a List Using a for loop we can iterate through each item in a list.<jupyter_code>for fruit in ['apple','banana','mango']:
    print("I like",fruit)<jupyter_output>I like apple
I like banana
I like mango<jupyter_text>DICTIONARY  How to create a dictionary?<jupyter_code>#initialisation

my_dict = {}
print(type(my_dict))<jupyter_output><class 'dict'><jupyter_text>You can create a Python dictionary by enclosing a comma-separated list of key-value pairs in curly braces { }. A colon “:” separates each key from its associated value:d = {    : ,    : ,      .      .      .    : }<jupyter_code># dictionary with integer keys

my_dict = {1:'apple', 2:'ball'}
print(my_dict)
# dictionary with mixed keys

my_dict = {'name':'John', 1:[2,4,3] }
print(my_dict)<jupyter_output>{'name': 'John', 1: [2, 4, 3]}<jupyter_text>We can also use the built-in function dict( ) to create a dictionary, like so:<jupyter_code># using dict()

my_dict = dict({1:'apple', 2:'ball'})
print(my_dict)<jupyter_output>{1: 'apple', 2: 'ball'}<jupyter_text>How to access elements from a dictionary?<jupyter_code>from IPython.display import Image
Image('images/access value.png')
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print ("dict['Name']:", dict['Name'])

print ("dict['Age']:", dict.get('Age'))<jupyter_output>dict['Age']: 7<jupyter_text>How to add or change elements in a dictionary? Since Python dictionaries are mutable, you can add elements or even change the values of the existing items contained in a dictionary. For example, dict[key] = ‘value’. To update an existing value in a dictionary, you have to use the built-in update( ) method. You must remember that while adding a value to a dictionary if the value already exists, the value gets updated otherwise a new key with the value is added to the dictionary.<jupyter_code>from IPython.display import Image
Image('images/add key-value.png')
my_dict = {'name':'Jack', 'age': 26}
print(my_dict)
# update value

my_dict['age'] = 27
print(my_dict)
# add item

my_dict['address'] = 'Downtown'
print(my_dict)<jupyter_output>{'name': 'Jack', 'age': 27, 'address': 'Downtown'}<jupyter_text>How to remove or delete elements from a dictionary?<jupyter_code>from IPython.display import Image
Image('images/del key-value.png')
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict)
# remove entry with key ‘Name’
del dict['Name'];
print(dict)
# remove all entries in dict
dict.clear(); 
print(dict)
# delete entire dictionary
del dict ; 
print(dict)<jupyter_output><empty_output><jupyter_text>How to loop through a dictionary?<jupyter_code>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
for x in dict:
    print(x)<jupyter_output>Name
Age
Class<jupyter_text>How to check if a key is present in a dictionary?<jupyter_code>thisdict = {

  'brand': 'Ferrari',

  'model': 'Daytone',

  'year': '1968'

}
if 'model' in thisdict:
    print("Yes, ‘model’ is one of the keys in the thisdict dictionary")<jupyter_output>Yes, ‘model’ is one of the keys in the thisdict dictionary<jupyter_text>How to determine the length of a dictionary?<jupyter_code>print(len(thisdict))<jupyter_output>3<jupyter_text>How to copy a dictionary?<jupyter_code>thisdict = {

  'brand':'Ford',

  'model': 'Mustang',

  'year': 1964

}
mydict = thisdict.copy()

print(mydict)<jupyter_output>{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{'fraction_non_alphanumeric': 0.1336658354114713, 'fraction_numerical': 0.017955112219451373, 'mean_word_length': 5.724346076458753, 'pattern_counts': {'":': 0, '<': 110, '<?xml version=': 0, '>': 110, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '33', 'dir': 'jupyter-structured-clean-dedup', 'id': '74524', 'license': 'MIT', 'n_tokens_mistral': 3710, 'n_tokens_neox': 3498, 'n_words': 1162, 'path': 'Day2/Lists And Dictionaries.ipynb', 'repo_name': 'rahulroy06/PythonSeries1.0', 'size': '10025'}