• Skip to primary navigation
  • Skip to main 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 Python | Convert a list of Tuples into Dictionary

Python | Convert a list of Tuples into Dictionary

Python | Convert case of elements in a list of strings

Leave a Comment


Given a list of strings, write a Python program to convert all string from lowercase/uppercase to uppercase/lowercase.

Input : ['GeEk', 'FOR', 'gEEKS']
Output: ['geeks', 'for', 'geeks']

Input : ['fun', 'Foo', 'BaR']
Output: ['FUN', 'FOO', 'BAR']


Method #1 : Convert Uppercase to Lowercase using map function

out = map(lambda x:x.lower(), ['GeEk', 'FOR', 'gEEKS'])

output = list(out)

print(output)

Output:


['geek', 'for', 'geeks']


Method #2: Convert Lowercase to Uppercase using List comprehension

input = ['fun', 'Foo', 'BaR']

lst = [x.upper() for x in input]

print(lst)

Output:


['FUN', 'FOO', 'BAR']




If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected] 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 [email protected] to report any issue with the above content.


Post navigation


Previous

first_page Python | Sum values for each key in nested dictionary










Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Amazon product price tracker using Python, Analysis of Algorithms, Aptitude, Array, Backtracking, Best Python libraries for Machine Learning, Binary Search (bisect) in Python, Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, C, Campus Ambassador Program, Careers, Check for balanced parentheses in Python, Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Constructors in Python, Contact Us, Contests, contribute.geeksforgeeks.org, contributed articles, Core Subjects ►, Counting the frequencies in a list using dictionary in Python, Courses, CS Subjects, CS Subjects ▼, CS Subjectwise ►, CSS, Data Structures, DBMS, Dealing with Rows and Columns in Pandas DataFrame, Decorators in Python, Decorators with parameters in Python, Design Patterns, Digital Electronics, Divide and Conquer, Dividing a Large file into Separate Modules in C/C++, DS ▼, Engg. Mathematics, Experienced Interviews, Face Detection using Python and OpenCV with webcam, Functions in Python, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Generating subarrays using recursion, Geometric Algorithms, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Heap, How to assign values to variables in Python and other languages, HTML, HTML & XML, ide.geeksforgeeks.org, Indentation and Comment in Python, Inheritance in Python, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, Java, Java and Python, JavaScript, Languages, Languages ►, Languages ▼, Last Minute Notes, Linear Regression Using Tensorflow, LinkedList, Machine Learning, Mathematical Algorithms, Matrix, Memoization using decorators in Python, Microprocessor, ML | Cancer cell classification using Scikit-learn, ML | Linear Regression, Multiple Choice Quizzes, Namespaces and Scope in Python, Operating Systems, Operator Overloading in Python, Output of Python Programs | (Dictionary), Pattern Searching, PHP, Placement Course, Polymorphism in Python, Practice, Practice Company Questions, Priority Queue in Python, Privacy Policy, Program Output, Project, Puzzles, Python, Python | Catching the ball game, Python | Convert a list into a tuple, Python | Convert a list of characters into a string, Python | Convert a list of multiple integers into a single integer, 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 | Convert list of string to list of list, Python | Convert list of strings and characters to list of characters, Python | Convert number to list of integers, Python | Convert set into a list, Python | Count occurrences of a character in string, Python | Delete rows/columns from DataFrame using Pandas.drop(), Python | Frequency of each character in String, Python | Generate QR Code using pyqrcode module, Python | Image Classification using keras, Python | Implementation of Movie Recommender System, Python | Implementation of Polynomial Regression, Python | Maximum sum of elements of list in a list of lists, Python | NLP analysis of Restaurant reviews, Python | Output Formatting, Python | Output using print() function, Python | Pandas Split strings into two List/Columns using str.split(), Python | Program to convert String to a List, Python | Program to generate one-time password (OTP), Python | range() method, Python | Remove empty strings from list of strings, Python | Sum values for each key in nested dictionary, Python for Data Science, Python in Competitive Programming, Python List, Python list sort(), Python list-programs, Python program to add two numbers, Python program to check whether a number is Prime or not, Python program to convert a list to string, Python program to find day of the week for a given date, Python program to print all Prime numbers in an Interval, Python program to swap two elements in a list, Python Programs, Python regex to find sequences of one upper case letter followed by lower case letters, Python String, Queue, Quizzes ▼, Randomized Algorithms, School Programming, Searching Algorithms, Skip to content, Software Engineering, Some rights reserved, Sorting Algorithms, SQL, Stack, Statement, Strings, Structuring Python Programs, Students ▼, Subjective Questions, Suggest an Article, Taking input from console in Python, Taking input in Python, Taking multiple inputs from user in Python, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Tree based DS ►, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Video Tutorials, Videos, Web Technology, What’s Difference?, Write an Article, Write Interview Experience

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:


Input : [1, 2, 3]
Output : 123

Input : [55, 32, 890]
Output : 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:

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:

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:

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:

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 [email protected] 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 [email protected] 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

  • Total Quality Management Questions and Answers – Agile Manufacturing
  • How to Become a Cyber Security Engineer?
  • How to Become a Software Architect?
  • 7 Best Languages to Learn IoT Development in 2020
  • REDIS Tutorial: Beginners
  • Privacy Policy
  • About
  • Contact US

© 2020 ProProgramming Privacy Policy About Contact Us