Greg
Greg

Reputation: 85

Position of tuple element in the list

I have list of tuples:

tuple_list = [(a, b), (c, d), (e, f), (g, h)]

How to get position of second element in tuple in second position of the list for example.

I need it because i want to change this list the way that every second element of tuple equals to first element from next tuple. Like this:

tuple_list = [(a, c), (c, e), (e, g), (g, h)]

Upvotes: 2

Views: 5237

Answers (3)

Picachieu
Picachieu

Reputation: 3782

Just use tuple_list[listindex][tupleindex], where listindex is the location within the list and tupleindex is the location within the tuple. For your example, do this:

loc = tuple_list[1][1]

Just be aware that tuples are immutable collections. If you want to change them, you should use lists instead. However, variables with a tuple value can still be reassigned to a new tuple. For example, this is legal:

x = ('a', 'b', 'c')
x = (1, 2, 3)

but this is not:

x = ('a', 'b', 'c')
x[0] = 1

See also: TutorialsPoint tutorial on lists and tuples.

Upvotes: 2

H. Ross
H. Ross

Reputation: 540

Tuples have indexes same as lists, therefore you can just grab the [0] index of the following tuple in the list. However, a catch is that tuples cannot be modified, therefore you must generate a new tuple for each assignment.

For example:

tuple_list = [(a, b), (c, d), (e, f), (g, h)]

for x in range(0, len(tuple_list) - 1): # Go until second to last tuple, because we don't need to modify last tuple
    tuple_list[x] = (tuple_list[x][0],tuple_list[x+1][0]) # Set tuple at current location to the first element of the current tuple and the first element of the next tuple

Will generate the desired result

Upvotes: 1

deleaf
deleaf

Reputation: 42

tuples in python can be accessed like arrays, using the index of the element

Upvotes: 0

Related Questions