Create a list from a list of tuples

tuple inside list python
python tuple
list of tuples c#
add tuple to list python
python return list or tuple
python list
python list of tuples to list of first elements
python list of lists

I have a list like this:

mylist = [(20, 'Start', '2008-10-10', 'TBS'),...,(20, 'End', '2008-11-09', 'NG'), 
          (21, 'Start', '2008-12-10', 'TBS'),...,(21, 'End', '2008-12-15', 'G'), 
          (22, 'Start', '2009-01-10', 'TBS'),...,(22, 'End', '2009-12-10', 'B'),..]

I put '...' in the example above to say there are other items for each id like 20, 21 and 22 in the list but I don't want them. The only items that I want are the items that include 'Start' or 'End'.(Other items have different words than these two words.)

I want to create a nested list like this:

[[20, 'Start', '2008-10-10', 'End', '2008-11-09', 'NG'] ,
 [21, 'Start', '2008-12-10', 'End', '2008-12-15', 'G'], 
 [22, 'Start', '2009-01-10', 'End', '2009-12-10', 'B']]

Here is my code:

code = 0
brr = []
for row in myList:
    if row[1] == "Start":
        arr = []
        code = row[0]
        arr.append([row[0], row[1], row[2]])
        continue

    if row[0] == code and row[1] == "End":
        arr.append([row[1], row[2], row[3]])
    brr.append(arr)
for k in brr:
    print(k)

But the problem is that it creates something like this:

[[[20, 'Start', '2008-10-10', 'End'], ['2008-11-09', 'NG']] ,
 [[20, 'Start', '2008-10-10', 'End'], ['2008-11-09', 'NG']] ,
 [[20, 'Start', '2008-10-10', 'End'], ['2008-11-09', 'NG']] ,
 [[21, 'Start', '2008-12-10', 'End'], ['2008-12-15', 'G']], 
 [[21, 'Start', '2008-12-10', 'End'], ['2008-12-15', 'G']],
 [[22, 'Start', '2009-01-10', 'End'], ['2009-12-10', 'B']]]

And for each items I have multiple rows in the list. I don't know why? Sorry if my question is too long.


Your brr.append(arr) is always adding an array for each row, that's why there are 6 elements in the ouput. Change brr.append(arr) to:

if arr not in brr:
    brr.append(arr)

As for the format, arr.append([row[0], row[1], row[2]]) adds a list of 3 elements, instead of 3 separate elements. Use extend instead.

Your final code should look like this:

code = 0
brr = []
for row in mylist:

    if row[1] == "Start":
        arr = []
        code = row[0]
        arr.extend([row[0], row[1], row[2]])
        # continue not needed here

    if row[0] == code and row[1] == "End":
        arr.extend([row[1], row[2], row[3]])

    if arr not in brr:
        brr.append(arr)

for k in brr:
    print(k)

Python program to create a list of tuples from given list having , We can use list comprehension to create a list of tuples. The first element will be simply an element and second element will be cube of that number. Below is  Given a list of tuples, write a Python program to convert it into list. Below are methods to convert list of tuples into list. Check out this Author's contributed articles. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.


You need to use arr.extend() function

arr = []
arr.append([1,2]) # arr = [[1,2]]
arr = []
arr.extend([1,2])  # arr = [1,2]

Convert list of tuples to list?, Using simple list comprehension: e = [(1,), (2,), (3,)] [i[0] for i in e]. will give you: [1, 2, 3]. Let's create a tuple from the same list of WoW classes above. With tuples we can "unpack" the values like this: You can also create a tuple from a list. Check out the Python reference documentation for more info on tuples. Now that we have a good intro to Python Lists and Tuples we can get to the meat of this tutorial.


You can achieve this pretty simply with itertools.groupby as well:

import itertools
from pprint import pprint

mylist = [
    (20, 'Start', '2008-10-10', 'TBS'),
    (20, 'Foo', '2008-10-10', 'TBS'),
    (20, 'End', '2008-11-09', 'NG'),

    (21, 'Start', '2008-12-10', 'TBS'),
    (21, 'End', '2008-12-15', 'G'),

    (22, 'Start', '2009-01-10', 'TBS'),
    (22, 'End', '2009-12-10', 'B'),
]

rows = (x for x in mylist if x[1] in ('Start', 'End'))
grouped = itertools.groupby(rows, key=lambda x: x[0])
output = [[k, *next(grp)[1:3], *next(grp)[1:4]] for k, grp in grouped]
pprint(output)

Output:

[[20, 'Start', '2008-10-10', 'End', '2008-11-09', 'NG'],
 [21, 'Start', '2008-12-10', 'End', '2008-12-15', 'G'],
 [22, 'Start', '2009-01-10', 'End', '2009-12-10', 'B']]

Lists and Tuples in Python – Real Python, It might make sense to think of changing the characters in a string. But you can't. In Python, strings are also immutable. The list is the first mutable data type you  Without bothering how that works under the covers, that means you can simply extend from List<T>, add a custom Add method to initialize your T, and you are done! public class TupleList<T1, T2> : List<Tuple<T1, T2>> { public void Add( T1 item, T2 item2 ) { Add( new Tuple<T1, T2>( item, item2 ) ); } }


please try this,

startlist=[]
endlist=[]
for item in mylist:
    if 'Start' in list(item):
        startlist.append(list(item))
    elif 'End' in list(item):
        endlist.append(list(item))
outlist=[i+j for i,j in zip(startlist,endlist)]     

Python Lists of Tuples, In this post we will talk about creating Python Lists of Tuples and how they can be used. Python Lists. Lists in Python are simply an array. You can still name the tuple properties AND still use var type inferencing (i.e. without repeating the property names) by supplying the names for the properties in the tuple creation, i.e. var list = Enumerable.Range(0, 10) .Select(i => (example: i, descrpt: $"{i}")) .ToList(); // Access each item.example and item.descrpt


Lists and Tuples, Make a list with three or four items, and then print a message that includes at least one item from your list. Your  Method 2 : Use of dict () method. This is a simple method of conversion from a list or tuple to a dictionary. Here we pass a tuple into the dict() method which converts the tuple into the corresponding dictionary.


Tuples, With no argument, it creates an empty tuple: >>> t = tuple() >>> print t (). If the argument is a sequence (string, list or tuple), the result is a tuple with the elements  Tuples are identical to lists in all respects, except for the following properties: Tuples are defined by enclosing the elements in parentheses (()) instead of square brackets ([]). Tuples are immutable. Here is a short example showing a tuple definition, indexing, and slicing: >>>


Optimization tricks in Python: lists and tuples, Empty lists vs. empty tuples. Empty tuple acts as a singleton, that is, there is always only one tuple with a length of zero. When creating an empty  Given a list, write a Python program to convert the given list into a tuple. Approach #1 : Using tuple (list_name). Typecasting to tuple can be done by simply using tuple (list_name). A small variation to the above approach is to use a loop inside tuple () . This essentially unpacks the list l inside a tuple literal which is created due to the