How to create a list of tuple from a string pythonically

Tuples from string

This is the problem: I want to make a list made of tuple like this

1 c:\openlearning

2 H:\python

I want to make them into tuples like this

(1, “c:\openlearning”), (2, “H:\python”)

I want to make it the easiest way as its possible, without writing too much stuff.

I am going to do it this way, with a list comprehension

myf = """H:\pylearning
C:\python""".splitlines()

myg = [(n+1,f) for n,f in enumerate(myf)]

print(myg)

# OUTPUT
>>> [('1', 'H:\\pylearning'), ('2', 'C:\\python')]

enumerate

The enumerate function returns a number for each item of the list, so that you can use it for various purposes like using indexes of the items of the list.

List comprehension

It is a ‘shortcut’ to make for loops in one line. You put your for loop into square brackets and then you put the variable that will iterate an iterable object (like a list) like f for f in myiterable and you will have memorized under a label a list with all the items in the iterable object. You can do operations on the variable (f in the example) to modify each element of the iterable object. For example:

numbers = [1,2,3,4]
square = [f**2 for f in numbers]

# OUTPUT

>>> square
[1, 4, 9, 16]

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.