Difference Between List and Tuple in Python with Example.

Difference Between List and Tuple

List and Tuple are the two most commonly used data structures in Python programming. They are used for storing objects of any type in python. In this article, we are going to discuss the difference between List and Tuple and their use cases with examples. 


What is a List in Python?

In Python, a list is a built-in data structure that represents an ordered collection of items or elements. It is a mutable sequence, which means you can change its content, and it can contain any type of data such as numbers, strings, or other objects. 

Example:

fruits = ['apple', 'banana', 'orange', 'kiwi']


What is a Tuple in Python?

A tuple is a built-in data structure that represents an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, which means that once a tuple is created, you cannot add, remove, or modify its elements.

Example:

my_tuple = (1, 'hello', 3.14)


Here is the important difference between List and Tuple:


1. Mutability: The list is mutable, which means you can add, remove or modify items after the list is created. On the other hand, tuples are immutable, which means that once the tuple is created, its content cannot be changed.

Example to show mutability of List and Tuple.

#creating a list and a tuple
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)

#changing the first element of the list
my_list[0] = 4

#trying to change the first element of the tuple will result in an error
my_tuple[0] = 4

print(my_list) #output: [4, 2, 3]
print(my_tuple) #output: TypeError: 'tuple' object does not support item assignment
Output:

2. Speed: The list is dynamic in nature, whereas the tuple is static in nature, and because of this tuple is faster than the list.


3. Syntax: A list is defined using square brackets [] while a tuple is defined using parentheses ().


4. UsageLists are typically used for storing collections of items that can be changed throughout the program. Tuples, on the other hand, are generally used for storing collections of items that should not be changed during the program's execution, such as a set of coordinates or a date.

Example Code:

#creating a list of days in a week
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

#creating a tuple of coordinates
coordinates = (10.0, 20.0)

#trying to change an item in weekdays will work
weekdays[2] = 'Woden-day'

#trying to change an item in coordinates will result in an error
coordinates[0] = 20.0

print(weekdays) #output: ['Monday', 'Tuesday', 'Woden-day', 'Thursday', 'Friday']
print(coordinates) #output: TypeError: 'tuple' object does not support item assignment

In this example, we can see that we changed an item in the weekday list successfully but trying to change an item in the coordinates tuple resulted in a TypeError.

Difference Between List and Tuple.

Python List Python Tuple
Lists are Mutable in nature. Tuples are immutable in nature.
Square brackets [] are used to define the List Parentheses () are used to define Tuples.
Iteration over a List is time-consuming. Iteration over Tuple is faster.
Insertion and Deletion operations are performed better on List. Accessing an element of Tuple is more appropriate.
List Consume more memory. Tuple Consumes less memory.
The list has many built-in functions. Tuple has very few built-in functions.

Lists are typically used for collections of items that can be changed, while tuples are used for collections of items that should not be changed.

Function Overloading in C++ with Example.

Function Overloading in C++

Function Overloading is a feature of Object Oriented Programming in C++ that allows us to create multiple functions with the same name but different parameters. When the same function name is overloaded with different work in the same scope then it is called function overloading.


Function overloading is based on the concept of polymorphism, which allows a function to take on different forms based on its input or context. 

Example:

//example of function overloading
int fun(){}
int fun(int a, int b){}
float fun(double num){}

Function overloading is an important concept to understand because we use function overloading many times in real-life programming. There are a few important points that we need to keep in mind, let's discuss each of them with examples.

Overloading Function with Different Parameter Types.

Function overloading is used to provide different implementations of a function for different types of inputs. A function can be overloaded based on the number or types of parameters. The return type of a function cannot be used to differentiate between overloaded functions.

C++ Example code:
//Overloading Function with different types of parameters.
#include<iostream>
using namespace std;

//function with integer type parameter
int sum(int a, int b) {
   return a + b;
}
//function with float type parameter
float sum(float a, float b) {
   return a + b;
}

int main(){
   //function call
   cout << "Sum of two integers: " << sum(5, 10) << endl;
   cout << "Sum of two floats: " << sum(3.4f, 4.6f) << endl;
}
Output:
Sum of two integers: 15
Sum of two floats: 8

In the above code, we have used the same function name 'sum()' with the same number of parameters but in one function we have passed float type and in another, we have passed integer type parameters.  

Overloading Function with Different Number of Parameters.

The overloaded functions must have different parameter lists, either in terms of the number of parameters or their types. Function overloading is determined at compile-time based on the number and type of arguments passed to the function.

C++ Example code:
//Overloading Function with different number of parameters.
#include<iostream>
using namespace std;

//function with three integer parameters
int sum(int a, int b, int c) {
   return a + b + c;
}
//function with two integer parameters
int sum(int a, int b) {
   return a + b;
}
//function with two float parameters
float sum(float a, float b) {
   return a + b;
}

int main(){
   //function call
   cout << "Sum of three integers: " << sum(5, 10, 5) << endl;
   cout << "Sum of two integers: " << sum(12, 5) << endl;
   cout << "Sum of two floats: " << sum(3.5f, 4.5f) << endl;
}
Output:
Sum of three integers: 20
Sum of two integers: 17
Sum of two floats: 8

In the above code, we have used the same function name sum() with the same return type but passing a different number of parameters.

Conclusion:
Function overloading improves readability and reduces code duplication by providing a common function name to related functionality. It is also used to provide default values for parameters.

Read More:

100 Indian Company to Work as a Software Engineer.

Company to Work as a Software Engineer.

Software engineering is a popular field due to its high demand in the tech industry. Software engineers design, develop, and maintain software systems for various applications and platforms. The demand for software engineers has increased due to the rise of technology and digital transformation in almost every industry. They work with different programming languages, frameworks, and tools to create software that meets specific user requirements.


Moreover, software engineering is a field that offers various career paths and opportunities for growth, including web development, mobile app development, software testing, data science, and more. With the increasing demand for technology-based solutions, software engineers are in high demand, and the demand is expected to grow in the future. Additionally, software engineering also offers competitive salaries, job flexibility, and a dynamic work environment, which makes it a popular career choice for many individuals.


Here I am sharing the list of 100 India-based companies where you can work as a Software Developer.


Company Name
Tata Consultancy Services
Infosys
Wipro
HCL Technologies
Tech Mahindra
Cognizant Technology Solutions
L&T Infotech
Capgemini
Accenture
IBM India
Hike Messenger
Zoho Corporation
Mindtree
Mphasis
Persistent Systems
Cybage Software
Kony Labs
InMobi
Sapient
CGI
Geometric
Hexaware Technologies
Tally Solutions
Yodlee Infotech
KPMG
Deloitte India
PwC India
EY India
Techjini
NetApp
McAfee
Novell Software Development
Akamai Technologies
Intel India
Google India
Microsoft India
Adobe India
Oracle India
Amazon India
Apple India
Uber India
Ola Cabs
Swiggy
Flipkart
Myntra
MakeMyTrip
Cleartrip
RedBus
Goibibo
Practo
HealthifyMe
Portea Medical
Medlife
1mg Technologies
Citrus Pay
Paytm
FreeCharge
PhonePe
Razorpay
Quick Heal Technologies
NASSCOM
NSE IT
Bombay Stock Exchange
National Informatics Centre
Centre for Development of Advanced Computing
Indian Space Research Organisation
Bharat Heavy Electricals
Hindustan Aeronautics
Bharat Electronics
National Thermal Power Corporation
Indian Oil Corporation
Oil and Natural Gas Corporation
Tata Motors
Mahindra & Mahindra
Maruti Suzuki India
Bajaj Auto
Hero MotoCorp
TVS Motor Company
Hindustan Unilever
Nestle India
Pepsico India
Coca-Cola India
ITC Limited
Tata Steel
Steel Authority of India
Larsen & Toubro
Aditya Birla Group
Reliance Industries
Bharat Petroleum
Hindustan Petroleum
GAIL
Coal India
NTPC Limited
Power Grid Corporation of India
Indian Railways
Delhi Metro Rail Corporation
Mumbai Metro Rail Corporation
Bangalore Metro Rail Corporation
GMR Group
Adani Group


There are many more companies in which you can work as a software engineer, if you have more suggestions you can share them in the comment section below.

Python Program to Find nth Fibonacci Number.

Given an integer 'n', write a Python program to print the nth Fibonacci number. 

The nth Fibonacci number is defined as the sum of the (n-1)th and (n-2)th Fibonacci numbers, where the 0th and 1st Fibonacci numbers are 0 and 1, respectively.(alert-success)

Example:

Example 1:
Input: n = 6
Output: 8
Explanation: 0, 1, 1, 2, 5, 8
0+1 = 1
1+1 = 2
2+3 = 5
3+5 = 8

Example 2:
Input: 10
Output: 55

We can solve this problem using multiple approaches, let's discuss each of them one by one and understand which approach is best for us.

Find Fibonacci Number using Recursion.

Python code:
# function to print nth Fibonacci number
def fibonacci_recursive(n):
    if n == 0 or n == 1:
        return n
    return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
# print value
print(fibonacci_recursive(10))
Output:
55
  • Time Complexity: O(2^n) - Exponential
  • Space Complexity: O(n) - Space required by the call stack of recursive calls


Find Fibonacci Number using Dynamic Programming.

In this approach, we use a list to store the Fibonacci numbers from 0 to n. We initialize the first two Fibonacci numbers (0 and 1) in the list, and then iterate over the remaining numbers from 2 to n, computing each Fibonacci number as the sum of the previous two numbers. Finally, we return the nth Fibonacci number from the list.

Python Code:
# Find Fibonacci number using Dynamic Programming
def fibonacci_dp(n):
    if n == 0 or n == 1:
        return n
    fib = [0, 1]
    for i in range(2, n+1):
        fib.append(fib[i-1] + fib[i-2])
    return fib[n]
# print output
print(fibonacci_dp(8))
Output:
21
  • Time Complexity: O(n) - Linear
  • Space Complexity: O(n) - Space required to store the list of Fibonacci numbers.


Fibonacci Number using Space-Optimized Dynamic Programming.

In this approach, we optimize the space complexity of the above dynamic programming approach by using only two variables to store the last two Fibonacci numbers. 

We initialize variables to 0 and 1, and then iterate over the remaining numbers from 2 to n, computing each Fibonacci number as the sum of the previous two numbers. After each iteration, we update the two variables to store the last two Fibonacci numbers. Finally, we return the last value of the second variable, which is the nth Fibonacci number.

Python Code:
# find fibonacci num space-optimized DP solution
def fibonacci_optimized(n):
    if n == 0 or n == 1:
        return n
    a, b = 0, 1
    for i in range(2, n+1):
        c = a + b
        a, b = b, c
    return b
#print output
print(fibonacci_optimized(10))
Output:
55
  • Time Complexity: O(n) - Linear
  • Space Complexity: O(1) - Constant space required to store only two variables (a and b)

Read More:

Python Program to Print Prime Numbers of a Given Interval.

Given two integer values 'start' and 'end' as an interval. Write a Python program to print all prime numbers present in this interval.

Prime numbers are positive integers greater than 1 that have no positive integer divisors other than 1 and themselves. To find prime numbers in a given interval, we need to check each number in the interval whether it is a prime number or not. Example: 2, 3, 5, 7, 11, etc. (alert-success)


Python Program to find Prime numbers in the given Interval.

# Function to check if a number is prime
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

# Function to find prime numbers in a given interval
def find_primes(start, end):
    prime_numbers = []
    for num in range(start, end+1):
        if is_prime(num):
            prime_numbers.append(num)
    return prime_numbers

# Example usage
start = 10
end = 50
print("Prime numbers between", start, "and", end, "are:")
print(find_primes(start, end))
Output:
Prime numbers between 10 and 50 are:
[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Explanation:
In the above program, to check if a number is a prime, we use a for loop that iterates from 2 to the square root of the number. If the number is divisible by any number in this range, it is not a prime number. Otherwise, it is a prime number.
  • Time Complexity: The overall time complexity is O(n*sqrt(n)) where n is the difference start and end interval. 
  • Space Complexity: The overall space complexity is O(n) because we are creating a list of prime numbers which can have a maximum size of n.

Find a Palindromic String in the Array.

Given an array of strings words[], write a program to return the first palindromic string in the array. If there is no such palindromic string present in the given array then return an empty string "".

Palindromic strings are those strings that read the same from left to right and from right to left. Example: radar(alert-passed)

Example: 
Input: words[] = {"abc", "cap", "radar", "racecar", "cook"}
Output: radar
Explanation: The first palindromic string is "radar"

Input: words[] = {"pet", "cable", "code"}
Output: ""
Explanation: There is no palindromic string, so returning an empty string.

There are multiple approaches to solving this problem, let's discuss each of them one by one:

Approach 1: Brute Force Approach.

In this approach, we are going to check each string in the array one by one if it is a palindrome. If palindrome is found then return it, else return an empty string.

Below is C++ Implementation:
//C++ Program to find Palindromic String
#include <iostream>
#include <string>
#include <vector>

using namespace std;

bool isPalindrome(string s) {
    int n = s.length();
    for (int i = 0; i < n / 2; i++) {
        if (s[i] != s[n - i - 1]) {
            return false;
        }
    }
    return true;
}

string firstPalindromicString(vector<string>& words) {
    for (string word : words) {
        if (isPalindrome(word)) {
            return word;
        }
    }
    return "";
}

int main() {
    vector<string> words = {"hello", "world", "racecar", "palindrome"};
    string result = firstPalindromicString(words);
    if (result == "") {
        cout << "No palindromic string found." << endl;
    } else {
        cout << "First palindromic string: " << result << endl;
    }
    return 0;
}
Output:
First palindromic string: racecar
  • Time Complexity: O(n * m^2), where n is the number of words in the array and m is the length of the longest word. This is because we need to check each word in the array, and for each word, we need to check if it is a palindrome, which takes O(m^2) time.
  • Space Complexity: O(1), since we are not using any additional space beyond the input array.

Approach 2: Using Two Pointers.

In this approach, we use two-pointers to compare characters from the beginning and end of each string. If the characters match, move the pointers inwards until they meet in the middle of the string. If the string is a palindrome, return it, otherwise move on to the next string in the array. 

Below is C++ Implementation:
//C++ Code for finding Palindromic String
#include <iostream>
#include <string>
#include <vector>

using namespace std;

bool isPalindrome(string s) {
    int i = 0, j = s.length() - 1;
    while (i < j) {
        if (s[i] != s[j]) {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

string firstPalindromicString(vector<string>& words) {
    for (string word : words) {
        if (isPalindrome(word)) {
            return word;
        }
    }
    return "";
}

int main() {
    vector<string> words = {"hello", "world", "racecar", "palindrome"};
    string result = firstPalindromicString(words);
    if (result == "") {
        cout << "No palindromic string found." << endl;
    } else {
        cout << "First palindromic string: " << result << endl;
    }
    return 0;
}
Output:
First palindromic string: racecar
  • Time Complexity: O(n * m), where n is the number of words in the array and m is the length of the longest word. This is because we need to check each word in the array, and for each word, we need to compare each character from the beginning and end of the word, which takes O(m) time.
  • Space Complexity: O(1), since we are not using any additional space beyond the input array.

Approach 3: Using Reverse String.

This approach is to reverse each string in the array and compare it to the original string. If they are equal, the string is a palindrome. Return the first palindrome found, or an empty string if no palindrome is found.

Below is C++ Implementation:
//C++ Code for Palindromic String
#include <iostream>
#include <string>
#include <vector>

using namespace std;
//function to reverse each string
string reverseString(string s) {
    int n = s.length();
    for (int i = 0; i < n / 2; i++) {
        char temp = s[i];
        s[i] = s[n - i - 1];
        s[n - i - 1] = temp;
    }
    return s;
}

string firstPalindromicString(vector<string>& words) {
    for (string word : words) {
        if (word == reverseString(word)) {
            return word;
        }
    }
    return "";
}

int main() {
    //array of string
    vector<string> words = {"hello", "world", "racecar", "palindrome"};
    //function call
    string result = firstPalindromicString(words);
    
    if (result == "") {
        cout << "No palindromic string found." << endl;
    } else {
        cout << "First palindromic string: " << result << endl;
    }
    return 0;
}
Output:
First palindromic string: racecar
  • Time Complexity: O(n * m), where n is the number of words in the array and m is the length of the longest word. This is because we need to check each word in the array, and for each word, we need to reverse it, which takes O(m) time, and then compare it to the original word, which takes another O(m) time.
  • Space Complexity: O(1), since we are not using any additional space beyond the input array.

Program to Find Number of Arithmetic Triplets.

Given a zero-based strictly increasing integer array arr[], and a positive integer diff. Write a program to return the number of unique arithmetic triplets.

Condition for Arithmetic Triplets:

  • Index i < j < k.
  • arr[j] - arr[i] == diff and,
  • arr[k] - arr[j] == diff (alert-passed)

Example:
Input: arr[] = {1, 3, 5, 6, 8, 11, 15}, diff = 2
Output: 1
Explanation:
(0, 1, 2) is an arithmetic triplet because 3 - 1 = 2 and 5 - 3 = 2

Input: arr[] = {0, 1, 4, 6, 7, 10}, diff = 3
Output: 2
Explanation:
(1, 2, 4) is an arithmetic triplet because both 7 - 4 = 3 and 4 - 1 = 3.
(2, 4, 5) is an arithmetic triplet because both 10 - 7 = 3 and 7 - 4 = 3.

There are multiple ways to solve this problem and here we will discuss brute-force and optimized solutions so you can get a better understanding of how to approach similar problems. 

Approach 1: Brute Force Approach.

As the given array contains only positive numbers and elements are in sorted order, we can easily solve this problem by using three nested loops and defining the arithmetic triplet condition inside the inner loop.

Below is the C++ Implementation:
//C++ program to find arithmetic triplets
#include<iostream>
using namespace std;

//function definition
int arithmeticTriplet(int arr[], int size, int diff){
    //variable to get the count
    int count = 0;

    for(int i = 0; i < size; i++){
        for(int j = i + 1; j < size; j++){
            for(int k = j + 1; k < size; k++){
                if((arr[j] - arr[i]) == diff && (arr[k] - arr[j]) == diff){
                    count++;
                }
            }
        }
    }
    return count;
}

int main(){
    int arr[] = {0, 1, 4, 6, 7, 10};
    int size = sizeof(arr)/sizeof(arr[0]);

    int diff = 3;

    cout<<arithmeticTriplet(arr, size, diff);

    return 0;
}
Output:
2
  • Time Complexity: O(n^3)
  • Space Complexity: O(1)
The time complexity of the solution using the above approach is very high which is a good solution for big-size data. We have to think of a better and more optimized solution which we are going to discuss in our next approach.

Approach 2: Using a Hashmap.

Using a hashmap to store unique elements will help us reduce our time complexity. 

Steps to follow:
  • Declare an unordered_map to keep track of unique elements of the array that we have seen so far and also initialize a count variable to count the number of arithmetic triplets. 
  • Iterate over the given array, for each element arr[i] check if arr[i] - diff and arr[i] - 2*diff are present in our unordered_map, if yes then increase the value of count by 1.
  • Insert the correct element arr[i] into the unordered_map so we can use this value to find out more arithmetic triplets.
  • Return the count after processing all the elements of the given array.
Below is C++ Implementation:
//C++ code for finding arithmetic triplets
#include <iostream>
#include <unordered_set>
using namespace std;

//function declaration
int countTriplets(int arr[], int n, int diff) {
    unordered_set<int> seen;
    int count = 0;

    for (int i = 0; i < n; i++) {
        if (seen.count(arr[i] - diff) && seen.count(arr[i] - 2 * diff)) {
            count++;
        }
        seen.insert(arr[i]);
    }

    return count;
}

int main() {

    int arr[] = {1, 3, 5, 6, 8, 11, 15};
    //size of array
    int n = sizeof(arr)/sizeof(arr[0]);

    int diff = 2;
    int count = countTriplets(arr, n, diff);
    cout << count << endl;

    return 0;
}
Output:
1
  • Time Complexity: O(n) where n is the length of the input array and we only need to loop over the array once.
  • Space Complexity: O(n) as we have used unordered_set to keep track of unique elements of the array.

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by templateszoo