1

I have the following python list in

[0,1,2,'def','ghi']

Now I want to convert above into another list of tuples by discarding first list item so for e.g. I want [(1,0),(2,1),('def',2),('ghi',3)]

I have the following code

point = [0,1,2,'def','ghi']
spliltm0 = split[1:]
ls = ()
int i = 0
for a in spliltm0:
   ls = (a,i++)

The above seems to be long code for Python, is there any shorter version of above code? I am super new to Python.

halfer
  • 19,824
  • 17
  • 99
  • 186
Umesh K
  • 13,436
  • 25
  • 87
  • 129

2 Answers2

3

That code isn't Python at all, since you do int i and i++, neither of which are Python*; also, strip() and split() are methods on strings, not lists.

Your result can be achieved in a one-line list comprehension:

result = [(elem, i) for i, elem in enumerate(point[1:])]

* i++ is syntactically valid in Python, but doesn't at all do what you think it does.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

You need to be clear about the basics of Python before asking in the Python Forum.

1) You cannot apply strip function on a 'list' object, It should be string object.

2) spliltm0 = split[1:], Here split is treated as string, and is not defined. Also split is a string method which should not be used as a variable for storing string.

3) int i = 0 This is a format of C/C++. Not applicable to Python

4)

for a in spliltm0:
   ls = (a,i++)

i++ is not available in Python. Refer to this link (Why are there no ++ and --​ operators in Python?)

Community
  • 1
  • 1
kvivek
  • 3,321
  • 1
  • 15
  • 17