• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar

Pro Programming

Professional way of Programming: Learn C, C++, Java, Python, Dot Net, Android the professional way

  • Home
  • C MCQs
  • C/C++ Programs
  • Java Programs
  • C#
  • Python
  • MySQL
  • Topics
    • Arrays
    • Strings
    • Link Lists
    • Trees
    • Shapes
  • Projects
  • Articles
  • Games
You are here: Home / Archives for not in

not in

Python | Convert a list of multiple integers into a single integer

Leave a Comment


Given a list of integers, write a Python program to convert the given list into a single integer.

Examples:

C++
1
2
3
4
5
6
7
8
9
10
 
 

<strong>Input :</strong> [1, 2, 3]&#13;
<strong>Output </strong>: 123&#13;
&#13;
<strong>Input :</strong> [55, 32, 890]&#13;
<strong>Output :</strong> 5532890
 
 

There are multiple approaches possible to convert the given list into a single integer. Let’s see each one by one.

Approach #1 : Naive Method
Simply iterate each element in the list and print them without space in between.

  

lst = [12, 15, 17]

  

for i in lst:

    print(i, end="")

Output:

C++
1
2
3
4
5
 
 
121517
 
 

 
Approach #2 : Using join()

Use the join() method of Python. First convert the list of integer into a list of strings( as join() works with strings only). Then, simply join them using join() method. It takes a time complexity of O(n).

def convert(list):

      

    

    s = [str(i) for i in list]

      

    

    res = int("".join(s))

      

    return(res)

  

list = [1, 2, 3]

print(convert(list))

Output:

C++
1
2
3
4
5
 
 
123
 
 

 
Approach #3 : Using map()

Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.

def convert(list):

      

    

    

    res = int("".join(map(str, list)))

      

    return res

  

list = [1, 2, 3]

print(convert(list))

Output:

C++
1
2
3
4
5
 
 
123
 
 

 
Approach #4 : Multiplying by corresponding power of 10

A more mathematical way, which does not require to convert the integer list to string list is, to multiply each integer element with its corresponding power of 10, and then summing it up. It takes a time complexity of O(n).

def convert(list):

      

    

    

  

    res = sum(d * 10**i for i, d in enumerate(list[::-1]))

      

    return(res)

  

list = [1, 2, 3]

print(convert(list))

Output:

C++
1
2
3
4
5
 
 
123
 
 

A small variation to this program leads to less computation in calculation of sum, i.e. using reduce(). This makes use of Horner’s rule, which factors the polynomial representing the number to reduce the number of multiplications.

res = functools.reduce(lambda total, d: 10 * total + d, list, 0)




If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :


thumb_up
Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.


Post navigation


Previous

first_page Python | Add new keys to a dictionary







Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, A single neuron neural network in Python, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Analysis of Algorithms, Aptitude, Array, Array in Python | Set 1 (Introduction and Functions), Backtracking, Basic calculator program using Python, Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, C, Campus Ambassador Program, Careers, class method vs static method in Python, Class or Static Variables in Python, Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Conditions and Functions), Contact Us, Contests, contribute.geeksforgeeks.org, contributed articles, Core Subjects ►, Count words in a given string, Courses, CS Subjects, CS Subjects ▼, CS Subjectwise ►, Data Structures, DBMS, Design Patterns, Digital Electronics, Divide and Conquer, DS ▼, Engg. Mathematics, Enumerate() in Python, Experienced Interviews, Expressions, extend()...), Find the first non-repeating character from a stream of characters, Function Decorators in Python | Set 1 (Introduction), Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Geometric Algorithms, Global and Local Variables in Python, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Heap, Heap queue (or heapq) in Python, How to check if a string is a valid keyword in Python?, How to input multiple values from user in one line in Python?, How to print without newline in Python?, How to split a string in C/C++, HTML & XML, ide.geeksforgeeks.org, Important differences between Python 2.x and Python 3.x with examples, insert(), Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, Iterations), Java, JavaScript, join() function in Python, Keywords in Python | Set 1, Keywords in Python | Set 2, Languages, Languages ►, Languages ▼, Last Minute Notes, len(), Linear Regression (Python Implementation), LinkedList, List Methods in Python | Set 1 (in, List Methods in Python | Set 2 (del, Lists, Machine Learning, map, Mathematical Algorithms, Matrix, max()...), Microprocessor, min(), Multiple Choice Quizzes, Multiplication of two Matrices in Single line using Numpy in Python, not in, NumPy in Python | Set 1 (Introduction), Object and Members, Object Oriented Programming in Python | Set 1 (Class, Operating Systems, Pattern Searching, Permutation and Combination in Python, PHP, Placement Course, pop(), Practice Company Questions, Print lists in Python (4 Different Ways), Print Single and Multiple variable in Python, Privacy Policy, Program Output, Program to print N minimum elements from list of integers, Project, Puzzles, Python, Python | Add new keys to a dictionary, Python | Check whether a list is empty or not, Python | Convert a list of characters into a string, Python | Convert a list of Tuples into Dictionary, Python | Convert a nested list into a flat list, Python | Convert an array to an ordinary list with the same items, Python | Program to convert String to a List, Python | Program to print duplicates from a list of integers, Python | Set 2 (Variables, Python | Set 3 (Strings, Python 3 basics, Python and Java?, Python code to move spaces to front of string in single traversal, Python Dictionary, Python GUI - tkinter, Python Input Methods for Competitive Programming, Python lambda (Anonymous Functions) | filter, Python Language Introduction, Python List, Python list | index(), Python list sort(), Python list-programs, Python map() function, Python program to find largest number in a list, Python program to find N largest elements from a list, Python program to print all negative numbers in a range, Python program to print all odd numbers in a range, Python program to right rotate a list by n, Python Slicing | Reverse an array in groups of given size, Python String, Python String | split(), Python Tuples, Queue, Quizzes ▼, Randomized Algorithms, range() vs xrange() in Python, reduce, Remove multiple elements from a list in Python, remove(), Rename multiple files using Python, Returning Multiple Values in Python, Reverse string in Python (5 different ways), School Programming, Searching Algorithms, Sets in Python, Skip to content, Software Engineering, Some rights reserved, sort(), Sorting Algorithms, SQL, Stack, Strings, Students ▼, Subjective Questions, Suggest a Topic, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Transpose a matrix in Single line in Python, Tree based DS ►, Tuples, Twitter Sentiment Analysis using Python, Type Conversion in Python, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Video Tutorials, Videos, Web Technology, What’s Difference?, When to use yield instead of return in Python?, Write an Article, Write Interview Experience

Primary Sidebar

Recent Posts

  • Solid State Chemistry Questions and Answers – Intensities
  • Python | Convert case of elements in a list of strings
  • Java String Array to String Example
  • 14. Two-way data binding with v-model
  • Solid State Chemistry Questions and Answers – Modern X-Ray Powder Techniques and their Applications
  • Privacy Policy
  • About
  • Contact US

© 2019 ProProgramming
 Privacy Policy About Contact Us