Combining every 2 string to 1 string

  • A+
Category:Languages

I have a list a

list = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF'] 

I want to get a list of strings like ["247400015203223811, DPF", "247400015203223813, ZPF"] combining every 2 strings to 1 string

I tried like

list2 = [] list = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']          for i in range(0, len(list), 2):             list2.append(list[i] + list[i]) 

is this even possible?

 


You almost had it, you can use this list comprehension:

mylist = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']  mylist2 = [mylist[i]+', '+mylist[i+1]for i in range(0,len(mylist),2)]  >>> mylist2 ['247400015203223811, DPF', '247400015203223813, ZPF'] 

Make sure you don't use the keyword list as a variable name, because it masks the python built-in type (I changed it to mylist instead)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: