PYTHON PART - 2







Python Lists

  • Lists are ordered collection of data items.
  • They store multiple items in a single variable.
  • List items are separated by commas and enclosed within square brackets [].
  • Lists are changeable meaning we can alter them after creation.

Example 1:

Explain
lst1 = [1,2,2,3,5,4,6] lst2 = ["Red", "Green", "Blue"] print(lst1) print(lst2)

Output:

[1, 2, 2, 3, 5, 4, 6]
['Red', 'Green', 'Blue']

 

Example 2:

details = ["Abhijeet", 18, "FYBScIT", 9.8]
print(details)

Output:

['Abhijeet', 18, 'FYBScIT', 9.8]

As we can see, a single list can contain items of different datatypes.




 

List Indexes

Each item/element in a list has its own unique index. This index can be used to access any particular item from the list. The first item has index [0], second item has index [1], third item has index [2] and so on.

Example:

colors = ["Red", "Green", "Blue", "Yellow", "Green"]
#          [0]      [1]     [2]      [3]      [4]

 

Accessing list items:

 

Positive Indexing:

As we have seen that list items have index, as such we can access items using these indexes.

Example:

Explain
colors = ["Red", "Green", "Blue", "Yellow", "Green"] # [0] [1] [2] [3] [4] print(colors[2]) print(colors[4]) print(colors[0])

Output:

Blue
Green
Red

 

Negative Indexing:

Similar to positive indexing, negative indexing is also used to access items, but from the end of the list. The last item has index [-1], second last item has index [-2], third last item has index [-3] and so on.

Example:

Explain
colors = ["Red", "Green", "Blue", "Yellow", "Green"] # [-5] [-4] [-3] [-2] [-1] print(colors[-1]) print(colors[-3]) print(colors[-5])

Output:

Green
Blue
Red

 

Check for item:

We can check if a given item is present in the list. This is done using the in keyword.

Explain
colors = ["Red", "Green", "Blue", "Yellow", "Green"] if "Yellow" in colors: print("Yellow is present.") else: print("Yellow is absent.")

Output:

Yellow is present.

 

Explain
colors = ["Red", "Green", "Blue", "Yellow", "Green"] if "Orange" in colors: print("Orange is present.") else: print("Orange is absent.")

Output:

Orange is absent.

 

Range of Index:

You can print a range of list items by specifying where do you want to start, where do you want to end and if you want to skip elements in between the range. 

Syntax:

List[start : end : jumpIndex]

Note: jump Index is optional. We will see this in given examples.

 

Example: printing elements within a particular range:

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[3:7])	#using positive indexes
print(animals[-7:-2])	#using negative indexes

Output:

['mouse', 'pig', 'horse', 'donkey']
['bat', 'mouse', 'pig', 'horse', 'donkey']

Here, we provide index of the element from where we want to start and the index of the element till which we want to print the values.

Note: The element of the end index provided will not be included. 

 

Example: printing all element from a given index till the end

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[4:])	#using positive indexes
print(animals[-4:])	#using negative indexes

Output:

['pig', 'horse', 'donkey', 'goat', 'cow']
['horse', 'donkey', 'goat', 'cow']

When no end index is provided, the interpreter prints all the values till the end.

 

Example: printing all elements from start to a given index

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[:6])	#using positive indexes
print(animals[:-3])	#using negative indexes

Output:

['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']
['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']

When no start index is provided, the interpreter prints all the values from start up to the end index provided. 

 

Example: print alternate values

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[::2])		#using positive indexes
print(animals[-8:-1:2])	#using negative indexes

Output:

['cat', 'bat', 'pig', 'donkey', 'cow']
['dog', 'mouse', 'horse', 'goat']

Here, we have not provided start and index, which means all the values will be considered. But as we have provided a jump index of 2 only alternate values will be printed. 

 

Example: printing every 3rd consecutive withing given range

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[1:8:3])

Output:

['dog', 'pig', 'goat']

Here, jump index is 3. Hence it prints every 3rd element within given index.


Add List Items

There are three methods to add items to list: append(), insert() and extend()

append():

This method appends items to the end of the existing list.

Example:

colors = ["voilet", "indigo", "blue"]
colors.append("green")
print(colors)

Output:

['voilet', 'indigo', 'blue', 'green']

 

What if you want to insert an item in the middle of the list? At a specific index?

 

insert():

This method inserts an item at the given index. User has to specify index and the item to be inserted within the insert() method.

Example:

Explain
colors = ["voilet", "indigo", "blue"] # [0] [1] [2] colors.insert(1, "green") #inserts item at index 1 # updated list: colors = ["voilet", "green", "indigo", "blue"] # indexs [0] [1] [2] [3] print(colors)

Output:

['voilet', 'green', 'indigo', 'blue']

 

What if you want to append an entire list or any other collection (set, tuple, dictionary) to the existing list?

 

extend():

This method adds an entire list or any other collection datatype (set, tuple, dictionary) to the existing list.

Example 1:

Explain
#add a list to a list colors = ["voilet", "indigo", "blue"] rainbow = ["green", "yellow", "orange", "red"] colors.extend(rainbow) print(colors)

Output:

['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']

 

Example 2:

Explain
#add a tuple to a list cars = ["Hyundai", "Tata", "Mahindra"] cars2 = ("Mercedes", "Volkswagen", "BMW") cars.extend(cars2) print(cars)

Output:

['Hyundai', 'Tata', 'Mahindra', 'Mercedes', 'Volkswagen', 'BMW']

 

Example 3:

Explain
#add a set to a list cars = ["Hyundai", "Tata", "Mahindra"] cars2 = {"Mercedes", "Volkswagen", "BMW"} cars.extend(cars2) print(cars)

Output:

['Hyundai', 'Tata', 'Mahindra', 'Mercedes', 'BMW', 'Volkswagen']

 

Example 4:

Explain
#add a dictionary to a list students = ["Sakshi", "Aaditya", "Ritika"] students2 = {"Yash":18, "Devika":19, "Soham":19} #only add keys, does not add values students.extend(students2) print(students)

Output:

['Sakshi', 'Aaditya', 'Ritika', 'Yash', 'Devika', 'Soham']

 

concatenate two lists:

you can simply concatenate two list to join two lists.

Example:

colors = ["voilet", "indigo", "blue", "green"]
colors2 = ["yellow", "orange", "red"]
print(colors + colors2)

Output:

['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']



Remove List Items

There are various methods to remove items from the list: pop(), remove(), del(), clear()

 

pop():

This method removes the last item of the list if no index is provided. If an index is provided, then it removes item at that specified index.

Example 1:

colors = ["Red", "Green", "Blue", "Yellow", "Green"]
colors.pop()        #removes the last item of the list
print(colors)

Output:

['Red', 'Green', 'Blue', 'Yellow']

 

Example 2:

colors = ["Red", "Green", "Blue", "Yellow", "Green"]
colors.pop(1)       #removes item at index 1
print(colors)

Output:

['Red', 'Blue', 'Yellow', 'Green']

 

What if you want to remove a specific item from the list?

 

remove():

This method removes specific item from the list.

Example:

colors = ["voilet", "indigo", "blue", "green", "yellow"]
colors.remove("blue")
print(colors)

Output:

['voilet', 'indigo', 'green', 'yellow']

 

del:

del is not a method, rather it is a keyword which deletes item at specific from the list, or deletes the list entirely.

Example 1:

colors = ["voilet", "indigo", "blue", "green", "yellow"]
del colors[3]
print(colors)

Output:

['voilet', 'indigo', 'blue', 'yellow']

 

Example 2:

colors = ["voilet", "indigo", "blue", "green", "yellow"]
del colors
print(colors)

Output:

NameError: name 'colors' is not defined 

We get an error because our entire list has been deleted and there is no variable called colors which contains a list.

 

What if we don’t want to delete the entire list, we just want to delete all items within that list?

 

clear():

This method clears all items in the list and prints an empty list.

Example:

colors = ["voilet", "indigo", "blue", "green", "yellow"]
colors.clear()
print(colors)

Output:

[]


Output:

['Harry', 'Sarah', 'juan', 'Anastasia', 'Steve']

 

What if the range of the index is more than the list of items provided?

In this case, all the items within the index range of the original list are replaced by the items that are provided.

Example:

names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[1:4] = ["juan", "Anastasia"]
print(names)

Output:

['Harry', 'juan', 'Anastasia', 'Steve']

 

What if we have more items to be replaced than the index range provided?

In this case, the original items within the range are replaced by the new items and the remaining items move to the right of the list accordingly.

Example:

names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2:3] = ["juan", "Anastasia", "Bruno", "Olga", "Rosa"]
print(names)

Output:

['Harry', 'Sarah', 'juan', 'Anastasia', 'Bruno', 'Olga', 'Rosa', 'Oleg', 'Steve']


List Comprehension

List comprehensions are used for creating new lists from other iterables like lists, tuples, dictionaries, sets, and even in arrays and strings.

 

Syntax:

List = [expression(item) for item in iterable if condition]

expression: it is the item which is being iterated.

iterable: it can be list, tuples, dictionaries, sets, and even in arrays and strings.

condition: condition checks if the item should be added to the new list or not. 

 

Example 1: accepts items with the small letter “o” in the new list 

names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if "o" in item]
print(namesWith_O)

Output:

['Milo', 'Bruno', 'Rosa']

 

Example 2: accepts items which have more than 4 letters

names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if (len(item) > 4)]
print(namesWith_O)

Output:

['Sarah', 'Bruno', 'Anastasia']


List Methods

We have discussed methods like append(), clear(), extend(), insert(), pop(), remove() before. Now we will learn about some more list methods:

 

sort(): This method sorts the list in ascending order.

Example 1:

Explain
colors = ["voilet", "indigo", "blue", "green"] colors.sort() print(colors) num = [4,2,5,3,6,1,2,1,2,8,9,7] num.sort() print(num)

Output:

['blue', 'green', 'indigo', 'voilet']
[1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]

 

What if you want to print the list in descending order?

We must give reverse=True as a parameter in the sort method.

Example:

Explain
colors = ["voilet", "indigo", "blue", "green"] colors.sort(reverse=True) print(colors) num = [4,2,5,3,6,1,2,1,2,8,9,7] num.sort(reverse=True) print(num)

Output:

['voilet', 'indigo', 'green', 'blue']
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 1, 1]

 

The reverse parameter is set to False by default.

Note: Do not mistake the reverse parameter with the reverse method.

 

reverse(): This method reverses the order of the list. 

Example:

Explain
colors = ["voilet", "indigo", "blue", "green"] colors.reverse() print(colors) num = [4,2,5,3,6,1,2,1,2,8,9,7] num.reverse() print(num)

Output:

['green', 'blue', 'indigo', 'voilet']
[7, 9, 8, 2, 1, 2, 1, 6, 3, 5, 2, 4]

 

index(): This method returns the index of the first occurrence of the list item.

Example:

Explain
colors = ["voilet", "green", "indigo", "blue", "green"] print(colors.index("green")) num = [4,2,5,3,6,1,2,1,3,2,8,9,7] print(num.index(3))

Output:

1
3

 

count(): Returns the count of the number of items with the given value.

Example:

colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.count("green"))

num = [4,2,5,3,6,1,2,1,3,2,8,9,7]

Output:

2
3

 

copy(): Returns copy of the list. This can be done to perform operations on the list without modifying the original list. 

Example:

Explain
colors = ["voilet", "green", "indigo", "blue"] newlist = colors.copy() print(colors) print(newlist)

Output:

['voilet', 'green', 'indigo', 'blue']
['voilet', 'green', 'indigo', 'blue']


Python Tuples

Tuples are ordered collection of data items. They store multiple items in a single variable. Tuple items are separated by commas and enclosed within round brackets (). Tuples are unchangeable meaning we can not alter them after creation.

 

Example 1:

Explain
tuple1 = (1,2,2,3,5,4,6) tuple2 = ("Red", "Green", "Blue") print(tuple1) print(tuple2)

Output:

(1, 2, 2, 3, 5, 4, 6)
('Red', 'Green', 'Blue')

 

Example 2:

details = ("Abhijeet", 18, "FYBScIT", 9.8)
print(details)

Output:

('Abhijeet', 18, 'FYBScIT', 9.8)


Tuple Indexes

Each item/element in a tuple has its own unique index. This index can be used to access any particular item from the tuple. The first item has index [0], second item has index [1], third item has index [2] and so on.

Example:

country = ("Spain", "Italy", "India", "England", "Germany")
#            [0]      [1]      [2]       [3]        [4]

 

Accessing tuple items:

 

I. Positive Indexing:

As we have seen that tuple items have index, as such we can access items using these indexes.

Example:

Explain
country = ("Spain", "Italy", "India", "England", "Germany") # [0] [1] [2] [3] [4] print(country[1]) print(country[3]) print(country[0])

Output:

Italy
England
Spain

 

II. Negative Indexing:

Similar to positive indexing, negative indexing is also used to access items, but from the end of the tuple. The last item has index [-1], second last item has index [-2], third last item has index [-3] and so on.

Example:

Explain
country = ("Spain", "Italy", "India", "England", "Germany") # [0] [1] [2] [3] [4] print(country[-1]) print(country[-3]) print(country[-4])

Output:

Germany
India
Italy

 

III. Check for item:

We can check if a given item is present in the tuple. This is done using the in keyword.

Example 1:

Explain
country = ("Spain", "Italy", "India", "England", "Germany") if "Germany" in country: print("Germany is present.") else: print("Germany is absent.")

Output:

Germany is present.

 

Example 2:

Explain
country = ("Spain", "Italy", "India", "England", "Germany") if "Russia" in country: print("Russia is present.") else: print("Russia is absent.")

Output:

Russia is absent.

 

IV. Range of Index:

You can print a range of tuple items by specifying where do you want to start, where do you want to end and if you want to skip elements in between the range.

 

Syntax:

Tuple[start : end : jumpIndex]

Note: jump Index is optional. We will see this in given examples.

 

Example: printing elements within a particular range:

animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[3:7])     #using positive indexes
print(animals[-7:-2])   #using negative indexes

Output:

('mouse', 'pig', 'horse', 'donkey')
('bat', 'mouse', 'pig', 'horse', 'donkey')

Here, we provide index of the element from where we want to start and the index of the element till which we want to print the values. 

Note: The element of the end index provided will not be included.

 

Example: printing all element from a given index till the end

animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[4:])      #using positive indexes
print(animals[-4:])     #using negative indexes

Output:

('pig', 'horse', 'donkey', 'goat', 'cow')
('horse', 'donkey', 'goat', 'cow')

When no end index is provided, the interpreter prints all the values till the end.

 

Example: printing all elements from start to a given index

animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[:6])      #using positive indexes
print(animals[:-3])     #using negative indexes

Output:

('cat', 'dog', 'bat', 'mouse', 'pig', 'horse')
('cat', 'dog', 'bat', 'mouse', 'pig', 'horse')

When no start index is provided, the interpreter prints all the values from start up to the end index provided. 

 

Example: print alternate values

animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[::2])     #using positive indexes
print(animals[-8:-1:2]) #using negative indexes

Output:

('cat', 'bat', 'pig', 'donkey', 'cow')
('dog', 'mouse', 'horse', 'goat')

Here, we have not provided start and index, which means all the values will be considered. But as we have provided a jump index of 2 only alternate values will be printed. 

 

Example: printing every 3rd consecutive withing given range

animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[1:8:3])

Output:

('dog', 'pig', 'goat')


ples are immutable, hence if you want to add, remove or change tuple items, then first you must convert the tuple to a list. Then perform operation on that list and convert it back to tuple.

Example:

Explain
countries = ("Spain", "Italy", "India", "England", "Germany") temp = list(countries) temp.append("Russia") #add item temp.pop(3) #remove item temp[2] = "Finland" #change item countries = tuple(temp) print(countries)

Output:

('Spain', 'Italy', 'Finland', 'Germany', 'Russia')

 

Thus, we convert the tuple to a list, manipulate items of the list using list methods, then convert list back to a tuple.

 

However, we can directly concatenate two tuples instead of converting them to list and back.

Example:

Explain
countries = ("Pakistan", "Afghanistan", "Bangladesh", "ShriLanka") countries2 = ("Vietnam", "India", "China") southEastAsia = countries + countries2 print(southEastAsia)

Output:

('Pakistan', 'Afghanistan', 'Bangladesh', 'ShriLanka', 'Vietnam', 'India', 'China')


Unpack Tuples

Unpacking is the process of assigning the tuple items as values to variables.

Example:

Explain
info = ("Marcus", 20, "MIT") (name, age, university) = info print("Name:", name) print("Age:",age) print("Studies at:",university)

Output:

Name: Marcus
Age: 20
Studies at: MIT

 

Here, the number of list items is equal to the number of variables.

 

But what if we have more number of items then the variables?

You can add an * to one of the variables and depending upon the position of variable and number of items, python matches variables to values and assigns it to the variables.

 

Example 1:

Explain
fauna = ("cat", "dog", "horse", "pig", "parrot", "salmon") (*animals, bird, fish) = fauna print("Animals:", animals) print("Bird:", bird) print("Fish:", fish)

Output:

Animals: ['cat', 'dog', 'horse', 'pig']
Bird: parrot
Fish: salmon

 

Example 2:

Explain
fauna = ("parrot", "cat", "dog", "horse", "pig", "salmon") (bird, *animals, fish) = fauna print("Animals:", animals) print("Bird:", bird) print("Fish:", fish)

Output:

Animals: ['cat', 'dog', 'horse', 'pig']
Bird: parrot
Fish: salmon

 

Example 3:

Explain
fauna = ("parrot", "salmon", "cat", "dog", "horse", "pig") (bird, fish, *animals) = fauna print("Animals:", animals) print("Bird:", bird) print("Fish:", fish)

Output:

Animals: ['cat', 'dog', 'horse', 'pig']
Bird: parrot
Fish: salmon


Comments

Popular posts from this blog

VLSI(Very Large Scale Integration)

C++ Programming complete Theory and Lecture

CMOS(Complementary metal oxide Semiconductor)