Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list index splitting and manipulation

My question seems simple, but for a novice to python like myself this is starting to get too complex for me to get, so here's the situation:

I need to take a list such as:

L = [(a, b, c), (d, e, d), (etc, etc, etc), (etc, etc, etc)]

and make each index an individual list so that I may pull elements from each index specifically. The problem is that the list I am actually working with contains hundreds of indices such as the ones above and I cannot make something like:

L_new = list(L['insert specific index here'])

for each one as that would mean filling up the memory with hundreds of lists corresponding to individual indices of the first list and would be far too time and memory consuming from my point of view. So my question is this, how can I separate those indices and then pull individual parts from them without needing to create hundreds of individual lists (at least to the point where I wont need hundreds of individual lines to create them).

like image 967
ImmortalxR Avatar asked Aug 03 '26 12:08

ImmortalxR


2 Answers

I might be misreading your question, but I'm inclined to say that you don't actually have to do anything to be able to index your tuples. See my comment, but: L[0][0] will give "a", L[0][1] will give "b", L[2][1] will give "etc" etc...

If you really want a clean way to turn this into a list of lists you could use a list comprehension:

cast = [list(entry) for entry in L]

In response to your comment: if you want to access across dimensions I would suggest list comprehension. For your comment specifically:

crosscut = [entry[0] for entry in L]

In response to comment 2: This is largely a part of a really useful operation called slicing. Specifically to do the referenced operation you would do this:

multiple_index = [entry[0:3] for entry in L]

Depending on your readability preferences there are actually a number of possibilities here:

list_of_lists = []
for sublist in L:
    list_of_lists.append(list(sublist))

iterator = iter(L)
for i in range(0,iterator.__length_hint__()):
    return list(iterator.next())
    # Or yield list(iterator.next()) if you want lazy evaluation
like image 78
Slater Victoroff Avatar answered Aug 06 '26 02:08

Slater Victoroff


What you have there is a list of tuples, access them like a list of lists

L[3][2]

will get the second element from the 3rd tuple in your list L

like image 35
Stephan Avatar answered Aug 06 '26 01:08

Stephan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!