Featured Post

Python map() and lambda() Use Cases and Examples

Image
 In Python, map() and lambda functions are often used together for functional programming. Here are some examples to illustrate how they work. Python map and lambda top use cases 1. Using map() with lambda The map() function applies a given function to all items in an iterable (like a list) and returns a map object (which can be converted to a list). Example: Doubling Numbers numbers = [ 1 , 2 , 3 , 4 , 5 ] doubled = list ( map ( lambda x: x * 2 , numbers)) print (doubled) # Output: [2, 4, 6, 8, 10] 2. Using map() to Convert Data Types Example: Converting Strings to Integers string_numbers = [ "1" , "2" , "3" , "4" , "5" ] integers = list ( map ( lambda x: int (x), string_numbers)) print (integers) # Output: [1, 2, 3, 4, 5] 3. Using map() with Multiple Iterables You can also use map() with more than one iterable. The lambda function can take multiple arguments. Example: Adding Two Lists Element-wise list1 = [ 1 , 2 , 3 ]

6 Exclusive List and Tuple Differences in Python

Here're quick differences between List and Tuple


Here're the quick differences between Tuple and List in Python. These are helpful for interviews and your project.

Tuple and List differences

List

  • Comma-separated elements inside a square bracket [] make a list.
  • The elements are indexed, which starts from '0'
  • These you need to enclose in a single quote and separate by a comma.
  • It can contain another list, which is called a NESTED list.
  • Use type() function to get the type of data it is.
  • The list is mutable (you can change the data). The objects (elements) can be of different data types. Here're examples on the List.

Tuple

  • The elements comma-separated and enclosed in parenthesis () 
  • The elements are indexed, which starts from '0'
  • It can have heterogeneous data (integer, float, string, list, etc.)
  • It is immutable. So you can't change the elements.
  • Use the type() function to get the type of data it is. 
  • Here're examples of Tuple.

List Example

#Illustration of creating a list 
new_list=[1, 2, 3, 4] 
print(new_list) 


# Homogeneous data elements 
new_list1=[1, "John", 55.5] 
print(new_list1) 


# Heterogeneous data elements 
new_list2=[111, [1, "Clara", 75.5]] 
# Nested list 
print(new_list2)


Output



[1, 2, 3, 4]
[1, ‘John’, 55.5]
[111, [1, ‘Clara’, 75.5]]



Tuple Example


#Illustration of unpacking a tuple 
 new_tuple2=(111, [1, "Clara", 75.5], (2, "Simon", 80.5)) 

# Nested tuple 
print(new_tuple2) x, y, z=new_tuple2 
print(x) 
print(y) 
print(z) 


Output



111
[1, ‘Clara’, 75.5]
(2, ‘Simon’, 80.5)

Comments

Popular posts from this blog

How to Fix datetime Import Error in Python Quickly

SQL Query: 3 Methods for Calculating Cumulative SUM

Python placeholder '_' Perfect Way to Use it