Python Forum
transform list to tuple with
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
transform list to tuple with
#1
Hi,

summary:
I have this output: [(1,), (2,), (3,), (4,), (5,)]
Question, how can I transform this to: ('1', '2','3','4',5')

Below is my trial

sId = cur1.fetchall()
print(sId)
Output:
[(1,), (2,), (3,), (4,), (5,)]
Here I change everything to an integer list
sId = cur1.fetchall()
sId2 = [x[0] for x in sId]
print(sId2)
Output:
[1, 2, 3, 4, 5]
Then I try to make it a string
try 1:
sId = cur1.fetchall()
sId2 = [x[0] for x in sId]
sId2 = tuple(sId2)
print(sId2)
Output:
(1,2,3,4,5)
try 2:
sId = cur1.fetchall()
sId2 = [x[0] for x in sId]
sId2 = (",".join(str(i) for i in sId2))
print(sId2)
Output:
1,2,3,4,5
Not yet what I need...

Can somebody help me to transform the original [(1,), (2,), (3,), (4,), (5,)] into ('1', '2','3','4',5') ?
Reply
#2
>>> lst = [(1,), (2,), (3,), (4,), (5,)]
>>> [str(x[0]) for x in lst]
['1', '2', '3', '4', '5']
>>> # If need tuple
>>> tuple([str(x[0]) for x in lst])
('1', '2', '3', '4', '5')
Reply
#3
(Nov-28-2017, 10:38 PM)snippsat Wrote:
>>> lst = [(1,), (2,), (3,), (4,), (5,)]
>>> [str(x[0]) for x in lst]
['1', '2', '3', '4', '5']
>>> # If need tuple
>>> tuple([str(x[0]) for x in lst])
('1', '2', '3', '4', '5')

thanks! works like a charm
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  using > < for tuple , list,... akbarza 3 490 Feb-05-2024, 01:18 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 496 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  [SOLVED] Looking for documentation on Reportlab's canvas.transform() function NeilUK 1 621 Aug-23-2023, 01:21 PM
Last Post: NeilUK
  Change font in a list or tuple apffal 4 2,704 Jun-16-2023, 02:55 AM
Last Post: schriftartenio
  search a list or tuple for a specific type ot class Skaperen 8 1,958 Jul-22-2022, 10:29 PM
Last Post: Skaperen
  Transform Dic to dataframe d9d9d 4 1,396 Apr-14-2022, 09:35 AM
Last Post: perfringo
  Transform 3 Columns into Single Column DaveG 8 1,890 Apr-04-2022, 08:42 AM
Last Post: Pedroski55
  why is my list a tuple CompleteNewb 7 2,283 Mar-17-2022, 10:09 PM
Last Post: CompleteNewb
  How to transform from wide to long format in python shantanu97 1 1,662 Nov-21-2021, 11:53 AM
Last Post: buran
  in a list or tuple Skaperen 6 93,432 May-16-2021, 09:59 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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