Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
split a item from a list
#1
Hello.
How can i split an item from a list,lets say list[0] is 12. I want to get the sum of 1 and 2 and replace list[0] with the sum. Which is 3. Any ideas?
Reply
#2
A simple function would do the trick. We just have to change the number into a string, turn the string into a list, change the list of strings into a list of numbers, and sum():

def digit_sum(number):
    value = str(number)
    digits = [int(x) for x in value]
    return sum(digits)
Reply
#3
Thank you for your reply.I will try to modify this function to work with a list
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,518 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Split string using variable found in a list japo85 2 1,300 Jul-11-2022, 08:52 AM
Last Post: japo85
Question Finding string in list item jesse68 8 1,871 Jun-30-2022, 08:27 AM
Last Post: Gribouillis
  how to easily create a list of already existing item CompleteNewb 15 3,541 Jan-06-2022, 12:48 AM
Last Post: CompleteNewb
  Remove an item from a list contained in another item in python CompleteNewb 19 5,731 Nov-11-2021, 06:43 AM
Last Post: Gribouillis
  count item in list korenron 8 3,472 Aug-18-2021, 06:40 AM
Last Post: naughtyCat
  Time.sleep: stop appending item to the list if time is early quest 0 1,879 Apr-13-2021, 11:44 AM
Last Post: quest
  How to run a pytest test for each item in a list arielma 0 2,369 Jan-06-2021, 10:40 PM
Last Post: arielma
  How do I add a number to every item in a list? john316 2 1,977 Oct-28-2020, 05:29 PM
Last Post: deanhystad
  Ignoring a list item hank4eva 2 2,123 Aug-17-2020, 08:40 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020