Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Print first n distinct permutations of string using itertools in Python
Next article icon

Python | Permutation of a given string using inbuilt function

Last Updated : 30 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to generate all the possible permutations of a given string. A permutation of a string is a rearrangement of its characters. For example, the permutations of “ABC” are “ABC”, “ACB”, “BAC”, “BCA”, “CAB”, and “CBA”. The number of permutations of a string with n unique characters is n! (factorial of n).

We can generate permutations of a string in Python using methods like inbuilt functions and recursion.

Using itertools.permutations

itertools module in Python provides a simple function called permutations that can generate all possible permutations of a string. This method is the easiest and most efficient, especially when working with built-in Python libraries.

Python
import itertools  s = "GFG" li = [''.join(p) for p in itertools.permutations(s)] print(li) 

Explanation:

  • itertools.permutations(s) generates all possible permutations of the string s, returning each permutation as a tuple.
  • ”.join(p) converts each tuple p into a string by concatenating its elements.
  • list comprehension collects all the joined strings (permutations) into a list.

Using Recursion

Recursion is a method where a function calls itself to solve smaller parts of a problem. In the case of generating permutations, we can break down the problem by selecting one character at a time and recursively permuting the rest of the string. This approach is a bit more complex than using itertools.permutations, but it can be useful if we want more control over the process.

Python
def permute(s, s2):     if len(s) == 0:         print(s2, end=' ')         return          for i in range(len(s)):         char = s[i]         left_s = s[0:i]         right_s = s[i+1:]         rest = left_s + right_s         permute(rest, s2 + char)  s1 = "GFG" s2 = "" permute(s1, s2) 

Output
GFG GGF FGG FGG GGF GFG 

Explanation:

  • If the string s is empty, print the accumulated answer.
  • For each character in s, remove the character and recursively permute the remaining characters while adding the character to answer.
  • Call permute(s, answer) with the initial string and an empty answer to start generating permutations.


Next Article
Print first n distinct permutations of string using itertools in Python

S

Shashank Mishra
Improve
Article Tags :
  • DSA
  • Python
  • Python string-programs
  • Python-Built-in-functions
  • python-string
Practice Tags :
  • python

Similar Reads

  • Permutations of a given string using STL
    Given a string s, the task is to return all unique permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CBA", "CAB" Input: s = "XY"Output: "XY", "YX"
    4 min read
  • Print first n distinct permutations of string using itertools in Python
    Given a string with duplicate characters allowed, print first n permutations of given string such that no permutation is repeated. Examples: Input : string = "abcab", n = 10 Output : aabbc aabcb aacbb ababc abacb abbac abbca abcab abcba acabb Input : string = "okok", n = 4 Output : kkoo koko kook ok
    2 min read
  • All permutations of a string using iteration
    A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation ( Source: Mathword ) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB We hav
    4 min read
  • Print all Unique permutations of a given string.
    Given a string that may contain duplicates, the task is find all unique permutations of given string in any order. Examples: Input: "ABC"Output: ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]Explanation: Given string ABC has 6 unique permutations as "ABC", "ACB", "BAC", "BCA", "CAB" and "CBA". Input: "A
    12 min read
  • Generate all permutation of a set in Python
    Permutation is an arrangement of objects in a specific order. Order of arrangement of object is very important. The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {
    2 min read
  • Create multiple copies of a string in Python by using multiplication operator
    In Python, creating multiple copies of a string can be done in a simple way using multiplication operator. In this article, we will focus on how to achieve this efficiently. Using multiplication operator (*)This method is the easiest way to repeat a string multiple times in Python. It directly gives
    1 min read
  • Numpy string operations | partition() function
    In the numpy.core.defchararray.partition() function, each element in arr, split the element as the first occurrence of sep, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containin
    1 min read
  • Minimum length of string having all permutation of given string.
    Given a string [Tex]S [/Tex]where [Tex]1\leq length\; of\; S\leq 26 [/Tex]. Assume that all the characters in [Tex]S [/Tex]are unique. The task is to compute the minimum length of a string which consists of all the permutations of the given string in any order. Note: All permutations must be present
    4 min read
  • Number of distinct permutation a String can have
    We are given a string having only lowercase alphabets. The task is to find out total number of distinct permutation can be generated by that string. Examples: Input : aab Output : 3 Different permutations are "aab", "aba" and "baa". Input : ybghjhbuytb Output : 1663200 A simple solution is to find a
    6 min read
  • numpy string operations | split() function
    numpy.core.defchararray.split(arr, sep=None, maxsplit=None) is another function for doing string operations in numpy.It returns a list of the words in the string, using sep as the delimiter string for each element in arr. Parameters: arr : array_like of str or unicode.Input array. sep : [ str or uni
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences