Splitting a tuple in to a list without splitting it in to individual characters

Viewed 1070

I am having issues with my Python code. I want to get the values from a tuple and put them in to lists. In the example below, I would like to get the artists in to one list, and the earnings in to another. Then put those in to a tuple.

def sort_artists(x):
    artist = []
    earnings = []
    z = (artist, earnings)
    for inner in x:
        artist += inner[0]
        earnings += inner[1]
    return z

artists = [("The Beatles", 270.8), ("Elvis Presley", 211.5), ("Michael Jackson", 183.9)]
print(sort_artists(artists))

I can print `inner[0] and that will give me 'The Beatles', but when I try to append it to the empty list, it splits it up in to individual letters. What is wrong?

The error (though I have tried it without the 'earnings' bit too, as well as using append, and other things:

Traceback (most recent call last):
  File "Artists.py", line 43, in <module>
    print(sort_artists(artists))
  File "Artists.py", line 31, in sort_artists
    earnings += inner[1]
TypeError: 'float' object is not iterable
Command exited with non-zero status 1

The desired output:

(['Elvis Presley', 'Michael Jackson', 'The Beatles'], [270.8, 211.5, 183.9]) 

This is what is currently happening (without the earnings bit):

(['T', 'h', 'e', ' ', 'B', 'e', 'a', 't', 'l', 'e', 's', 'E', 'l', 'v', 'i', 's', ' ', 'P', 'r', 'e', 's', 'l', 'e', 'y', 'M', 'i', 'c', 'h', 'a', 'e', 'l', ' ', 'J', 'a', 'c', 'k', 's', 'o', 'n'], []) 
4 Answers

you can use the built-in function zip to split the lists in one short expression:

def sort_artists(x):
    return tuple(list(t) for t in zip(*x))

artists = [("The Beatles", 270.8), ("Elvis Presley", 211.5), ("Michael Jackson", 183.9)]
print(sort_artists(artists))

Output:

(['The Beatles', 'Elvis Presley', 'Michael Jackson'], [270.8, 211.5, 183.9])

try this code :

def sort_artists(x):
    artist = []
    earnings = []
    z = (artist, earnings)
    for inner in x:
        artist.append(inner[0])
        earnings.append(inner[1])
    return z

artists = [("The Beatles", 270.8), ("Elvis Presley", 211.5), ("Michael Jackson", 183.9)]
print(sort_artists(artists))

output:

(['The Beatles', 'Elvis Presley', 'Michael Jackson'], [270.8, 211.5, 183.9])
def sort_artists(x):
    artist = []
    earnings = [] 
    for i in range(len(x)):
        artist.append(x[i][0])
        earnings.append(x[i][1])
    return (artist,earnings)

we can access element of list by it position

print(artist[0]) 
#o/p
('The Beatles', 270.8)

now we can unpack the tuple using index as well

#for artist
print(artist[0][0])
o/p
'The Beatles'

#for earnings
print(artist[0][1])
o/p
270.8
def sort_artists(x):
    artist = []
    earnings = []
    z = (artist, earnings)
    for inner in x:
        artist.append(inner[0])
        earnings.append(inner[1])
    artist.sort()
    earnings.sort()
    earnings.reverse()
    return z
Related