-3

I have this python code, yet it adds parenthesis to the enumeration. I don't need the parenthesis, so how do I do this in python? All I need is just to enumerate the list. this is what it does is

num =[(0, '1'), (1, '7'), (2, '11'), (3, '13')

this is my code

num =['1', '7', '11', '13']
print (list(enumerate(num,0)))

I need this below, but I don't the code.

num = [1,'1', 2,'7',3,'11',4,'13'] 
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
Tom E. O'Neil
  • 527
  • 4
  • 10

4 Answers4

4

Simply run a loop as below:

num =['1', '7', '11', '13']
final_list = list()
for index, i in enumerate(num):
    final_list.extend((index, i))

print(final_list)
[0, '1', 1, '7', 2, '11', 3, '13']
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36
1

Use itertools.chain.from_iterable:

from itertools import chain

num =['1', '7', '11', '13']
result = list(chain.from_iterable(enumerate(num)))
print(result)

Output:

[0, '1', 1, '7', 2, '11', 3, '13']
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
1

From you output you mean enumerate(num,1).

Just another short way.

We can add into a empty list after converting tuple to list. + here concats two lists

import functools
functools.reduce(lambda acc,x: acc + list(x),enumerate(num,1),[])

acc is [] is empty list initially and adding like ['hello'] + [1,2] = ['hello',1,2]

Output

[1, '1', 2, '7', 3, '11', 4, '13']
Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40
0

It is similar to Yugandhar Chaudhari answer.

I use map(list, ...) to convert tuples to lists and then I can add all lists to empty list [] using sum() instead of + and reduce()

num = ['1', '7', '11', '13']

print(sum(map(list, enumerate(num, 1)), []))
furas
  • 134,197
  • 12
  • 106
  • 148