0

I'm trying to convert ['25', '25', '10', '1', '50', '25', '140', '30'] into [(25,25),(10,1),(50,25),(140,30)] but not sure how. I tried something like a = [tuple(val) for val in w] but wasn't sure where to go from there.

Thanks

Levin Kent
  • 33
  • 4
  • 1
    Does this answer your question? [Pairs from single list](https://stackoverflow.com/questions/4628290/pairs-from-single-list) – Chris Oct 22 '21 at 04:13

3 Answers3

1

Iterate through your list 2 items at a time:

data = ['25', '25', '10', '1', '50', '25', '140', '30']

l = []
for i in range(0, len(data), 2):
    l.append((data[i], data[i+1]))

print(l)
QuantumMecha
  • 1,514
  • 3
  • 22
0

To yield two items at the same time, you could try this:

data = ['25', '25', '10', '1', '50', '25', '140', '30']
result = list(zip(map(eval, data[0::2]), map(eval, data[1::2])))
0

My logic: we've to iterate the list and add it to another empty list. Let's do it with while loop. We'll take a variable i which starts from 0 (because index starts from 0). Then we'll use while loop, while i<len(list) (because last index is len-1) and we'll make a tuple of list[i] and list[i+1] and append it to empty list. Updation value of i will be 2 because next pair has to be from +2 index. Your code:

x=["1","2","3","4","5","6"] #example
i=0
x1=[]
while i<len(x):
    v=(int(x[i]),int(x[i+1]))
    x1.append(v)
    i+=2

print(x1)