List to tuples in Python

convert list to list of tuples python
python list
tuple in python
python tuple append
python tuple methods
write a python program to remove an item from a tuple
python tuple vs list
list to tuple scala

I have a list in python, like this:

test = ['Vlan101', '1.1.1.0/24', 'Vlan111', '2.1.1.0/24', 'Vlan701', '3.1.1.0/24', 'Vlan703', '4.1.1.0/24', '5.5.5.0/24']

I would like tuples created out of it like below:

Vlan101,1.1.1.0/24
Vlan111,2.1.1.0/24
Vlan701,3.1.1.0/24
Vlan703,4.1.1.0/24, 5.5.5.0/24

The important thing is the last one, which has 2 values for the same key. This has been headscratcher for me.

You can use itertools.groupby() + zip() here:

from itertools import groupby

test = [
    "Vlan101",
    "1.1.1.0/24",
    "Vlan111",
    "2.1.1.0/24",
    "Vlan701",
    "3.1.1.0/24",
    "Vlan703",
    "4.1.1.0/24",
    "5.5.5.0/24",
]

print(
    [
        (x,) + y
        for x, y in zip(
            (x_ for x_ in test if x_.startswith("Vlan")),
            (
                tuple(g)
                for k, g in groupby(test, key=lambda x__: x__.startswith("Vlan"))
                if not k
            ),
        )
    ] 
)

# [('Vlan101', '1.1.1.0/24'), ('Vlan111', '2.1.1.0/24'), ('Vlan701', '3.1.1.0/24'), ('Vlan703', '4.1.1.0/24', '5.5.5.0/24')]

Convert list to tuple in Python, It should work fine. Don't use tuple , list or other special names as a variable name. It's probably what's causing your problem. >>> l = [4,5,6]  Python | Convert a list into a tuple filter_none edit close play_arrow link brightness_4 code. A small variation to the above approach is to use a loop edit close. play_arrow. link brightness_4 code. A small variation to the above approach is to use a loop inside tuple () . This essentially

Can use zip+iter for a generalized way of doing this

i = len(test)%2
s = iter(test[:-(2+i)])
[x for x in zip(s,s)] + [tuple(test[-(2+i):])]

Outputs

[('Vlan101', '1.1.1.0/24'),
 ('Vlan111', '2.1.1.0/24'),
 ('Vlan701', '3.1.1.0/24'),
 ('Vlan703', '4.1.1.0/24', '5.5.5.0/24')]

If you want the outer object to also be a tuple

tuple(x for x in zip(s,s)) + (tuple(test[-(2+i):]),)

(('Vlan101', '1.1.1.0/24'),
 ('Vlan111', '2.1.1.0/24'),
 ('Vlan701', '3.1.1.0/24'),
 ('Vlan703', '4.1.1.0/24', '5.5.5.0/24'))

Python: Convert a list to a tuple, Python Code: #Convert list to tuple listx = [5, 10, 7, 4, 15, 3] print(listx) #use the tuple() function built-in Python, passing as parameter the list  Expanding on eumiro's comment, normally tuple (l) will convert a list l into a tuple: In [1]: l = [4,5,6] In [2]: tuple Out[2]: <type 'tuple'> In [3]: tuple(l) Out[3]: (4, 5, 6) However, if you've redefined tuple to be a tuple rather than the type tuple: In [4]: tuple = tuple(l) In [5]: tuple Out[5]: (4, 5, 6)

The second, third, etc. elements of your tuples look like ip-addresses. You can use a regex to recognise the specific format. (I'm taking the risk of assuming you'll be playing around with ip-addresses).

Here's another solution, less cleaner than Rafael's or RoadRunner's, but allows for an arbitrary number of addresses.

import re

test = [
        'Vlan101',
        '1.1.1.0/24',
        'Vlan111',
        '2.1.1.0/24',
        'Vlan701', 
        '3.1.1.0/24', 
        'Vlan703', 
        '4.1.1.0/24', 
        '5.5.5.0/24']

result = [[]]  # we first store the stuff as lists to allow for appending
for item in test:

    # matches ipaddresses with xxx.xxx.xxx.xxx/xx
    if re.match(r'\d{,3}\.\d{,3}\.\d{,3}\.\d{,3}/\d+', item):
        result[-1].append(item)    # appends an ipaddress
    else:
        result.append([item])      # appends a new 'Vlan...' (i.e. anything but an ipaddress)

tups = list(map(tuple, result))    # cast each of the lists into tuples

print(result)
print(tups)

Output:

[[], ['Vlan101', '1.1.1.0/24'], ['Vlan111', '2.1.1.0/24'], ['Vlan701', '3.1.1.0/24'], ['Vlan703', '4.1.1.0/24', '5.5.5.0/24']]
[(), ('Vlan101', '1.1.1.0/24'), ('Vlan111', '2.1.1.0/24'), ('Vlan701', '3.1.1.0/24'), ('Vlan703', '4.1.1.0/24', '5.5.5.0/24')]

The empty [] and () are there at the beginning in case your test list starts off immediately with addresses (it's to provide a fall-back for result[-1]).

If you wish to remove those results simply do a slice

print(tups[1:])

Output:

[('Vlan101', '1.1.1.0/24'), ('Vlan111', '2.1.1.0/24'), ('Vlan701', '3.1.1.0/24'), ('Vlan703', '4.1.1.0/24', '5.5.5.0/24')]

Lists and Tuples in Python – Real Python, Python Lists. In short, a list is a collection of arbitrary objects, somewhat akin to an array in many other programming languages but more flexible. Lists are  Lists and tuples are arguably Python’s most versatile, useful data types.You will find them in virtually every nontrivial Python program. Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics of lists and tuples.

Convert Python List to Tuple, tuple is a builtin Python class that can take any iterable as argument for its constructor and return a tuple object. In the following example, we take a list and convert  #Convert list to tuple listx = [5, 10, 7, 4, 15, 3] print(listx) #use the tuple () function built-in Python, passing as parameter the list tuplex = tuple(listx) print(tuplex)

Python Lists of Tuples, Both lists and tuples in Python are handy elements to use for structuring data. Take a look at these instructional examples of how to use each of  Tuples are very similar to lists, but tuples are immutable. This means after they are created you can't change them. Let's create a tuple from the same list of WoW classes above. In: awesomeTuple=

5. Data Structures, If no index is specified, a.pop() removes and returns the last item in the list. Though tuples may seem similar to lists, they are often used in different situations​  A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. Example. Create a Tuple: thistuple = ("apple", "banana", "cherry") print(thistuple) Try it Yourself ».

Comments
  • the last one would be a list tho.
  • Please show what you have tried so far.
  • @felipsmartins what do you mean?
  • Will the first item in a row always start with "Vlan"?
  • This appears to be the best solution among all provided. Thanks, everyone for the help.
  • it doesn't generalize
  • Obviously depends on what you believe generalize is. I assumed it works for both all pairs and all pairs + triple at the end
  • take 2 pairs in between and it breaks. OP might not needed it but just mentioning.
  • Yeah we can think of numerous scenarios and no solutions will cover them all ;) this assumed following structure: key1,val1,key2,val2,... thanks for commenting