If input_list = [i,love,python], the output should be the string i love python.

reduce() in Python

The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.This function is defined in “functools” module.

Working :

  • At first step, first two elements of sequence are picked and the result is obtained.
  • Next step is to apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored.
  • This process continues till no more elements are left in the container.
  • The final returned result is returned and printed on console.




# python code to demonstrate working of reduce()
# importing functools for reduce()
import functools
# initializing list
lis = [1, 3, 5, 6, 2, ]
# using reduce to compute sum of list
print("The sum of the list elements is : ", end="")
print(functools.reduce(lambda a, b: a+b, lis))
# using reduce to compute maximum element from list
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))
Output The sum of the list elements is : 17 The maximum element of the list is : 6

Output:

The sum of the list elements is : 17 The maximum element of the list is : 6

Using Operator Functions



reduce() can also be combined with operator functions to achieve the similar functionality as with lambda functions and makes the code more readable.




# python code to demonstrate working of reduce()
# using operator functions
# importing functools for reduce()
import functools
# importing operator for operator functions
import operator
# initializing list
lis = [1, 3, 5, 6, 2, ]
# using reduce to compute sum of list
# using operator functions
print("The sum of the list elements is : ", end="")
print(functools.reduce(operator.add, lis))
# using reduce to compute product
# using operator functions
print("The product of list elements is : ", end="")
print(functools.reduce(operator.mul, lis))
# using reduce to concatenate string
print("The concatenated product is : ", end="")
print(functools.reduce(operator.add, ["geeks", "for", "geeks"]))
Output The sum of the list elements is : 17 The product of list elements is : 180 The concatenated product is : geeksforgeeks

Output

The sum of the list elements is : 17 The product of list elements is : 180 The concatenated product is : geeksforgeeks

reduce() vs accumulate()

Both reduce() and accumulate() can be used to calculate the summation of a sequence elements. But there are differences in the implementation aspects in both of these.

  • reduce() is defined in “functools” module, accumulate() in “itertools” module.
  • reduce() stores the intermediate result and only returns the final summation value. Whereas, accumulate() returns a iterator containing the intermediate results. The last number of the iterator returned is summation value of the list.
  • reduce(fun,seq) takes function as 1st and sequence as 2nd argument. In contrast accumulate(seq,fun) takes sequence as 1st argument and function as 2nd argument.




# python code to demonstrate summation
# using reduce() and accumulate()
# importing itertools for accumulate()
import itertools
# importing functools for reduce()
import functools
# initializing list
lis = [1, 3, 4, 10, 4]
# printing summation using accumulate()
print("The summation of list using accumulate is :", end="")
print(list(itertools.accumulate(lis, lambda x, y: x+y)))
# printing summation using reduce()
print("The summation of list using reduce is :", end="")
print(functools.reduce(lambda x, y: x+y, lis))
Output The summation of list using accumulate is :[1, 4, 8, 18, 22] The summation of list using reduce is :22

Output:

The summation of list using accumulate is :[1, 4, 8, 18, 22] The summation of list using reduce is :22

reduce() function with three parameters

Reduce function i.e. reduce() function works with 3 parameters in python3 as well as for 2 parameters. To put it in a simple way reduce() places the 3rd parameter before the value of the second one, if it’s present. Thus, it means that if the 2nd argument is an empty sequence, then 3rd argument serves as the default one.

Here is an example :(This example has been take from the functools.reduce() documentation includes a Python version of the function:




# Python program to illustrate sum of two numbers.
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
value = next(it)
else:
value = initializer
for element in it:
value = function(value, element)
return value
# Note that the initializer, when not None, is used as the first value instead of the first value from iterable , and after the whole iterable.
tup = (2,1,0,2,2,0,0,2)
print(reduce(lambda x, y: x+y, tup,6))
# This code is contributed by aashutoshjha
Output 15

This article is contributed by Manjeet Singh(S.Nandini). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

If input_list = [i,love,python], the output should be the string i love python.




Article Tags :
Python

Python: Concatenate all elements in a list into a string and return it

Last update on September 01 2020 10:25:53 (UTC/GMT +8 hours)

Input a List in Python

As you might already know, in order to accept an input from the user in Python, we can make use of the input() function. When used, it enables the programmer to accept either a string, integer or even a character as an input from the user. But when it comes to accepting a list as an input, the approach we follow is slightly different.

This how to input a List in Python article, will address main areas of concern

Find out our Python Training in Top Cities/Countries

IndiaUSAOther Cities/Countries
BangaloreNew YorkUK
HyderabadChicagoLondon
DelhiAtlantaCanada
ChennaiHoustonToronto
MumbaiLos AngelesAustralia
PuneBostonUAE
KolkataMiamiDubai
AhmedabadSan FranciscoPhilippines

Splitting, Concatenating, and Joining Strings in Python

by Kyle Stratis basics python
Mark as Completed
Tweet Share Email

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Splitting, Concatenating, and Joining Strings in Python

There are few guarantees in life: death, taxes, and programmers needing to deal with strings. Strings can come in many forms. They could be unstructured text, usernames, product descriptions, database column names, or really anything else that we describe using language.

With the near-ubiquity of string data, it’s important to master the tools of the trade when it comes to strings. Luckily, Python makes string manipulation very simple, especially when compared to other languages and even older versions of Python.

In this article, you will learn some of the most fundamental string operations: splitting, concatenating, and joining. Not only will you learn how to use these tools, but you will walk away with a deeper understanding of how they work under the hood.

Take the Quiz: Test your knowledge with our interactive “Splitting, Concatenating, and Joining Strings in Python” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Take the Quiz »

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Python List To String: 4 Easy Ways To Convert List To String

  • Posted on : December 20, 2021
  • Modified: December 28, 2021

  • Author : SPEC INDIA
  • Category : Python
Share on Facebook Share
0
Share on TwitterTweet
0
Share on LinkedIn Share

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Readability counts.

This is the philosophy of Python programming language summarized in the document The Zen of Python.

Readability in any programming language is considered important as it helps developers code faster, clear, and in an efficient way. Python is consistently ranked as one of the most popular programming languages and used by a large number of organizations that include world-famous organizations such as Facebook, Amazon, Instagram, Spotify, CERN, NASA, Wikipedia, Google, Reddit, ILM, ITA, and many more.

Python offers simpler, less-cluttered, and concise syntax, making the language to be fun to use. This reflects even in simple programs like Python list to string.

In this article, we will see how to convert a list to string in Python.

If input_list = [i,love,python], the output should be the string i love python.
If input_list = [i,love,python], the output should be the string i love python.