How to extract the n-th elements from a list of tuples?

python get first element of tuple in list
python list of tuples
write a for loop that saves the second element of each tuple into a list called seconds.
how to access elements in a list of tuples in python
python tuples
python get nth element of list of lists
how to create a list of tuples in python
tuple inside list python

I'm trying to obtain the n-th elements from a list of tuples.

I have something like:

elements = [(1,1,1),(2,3,7),(3,5,10)]

I wish to extract only the second elements of each tuple into a list:

seconds = [1, 3, 5]

I know that it could be done with a for loop but I wanted to know if there's another way since I have thousands of tuples.

n = 1 # N. . .
[x[n] for x in elements]

How to extract the n-th elements from a list of tuples?, n = 1 # N. . . [x[n] for x in elements]. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

This also works:

zip(*elements)[1]

(I am mainly posting this, to prove to myself that I have groked zip...)

See it in action:

>>> help(zip)

Help on built-in function zip in module builtin:

zip(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.

>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> zip(*elements)
[(1, 2, 3), (1, 3, 5), (1, 7, 10)]
>>> zip(*elements)[1]
(1, 3, 5)
>>>

Neat thing I learned today: Use *list in arguments to create a parameter list for a function...

Note: In Python3, zip returns an iterator, so instead use list(zip(*elements)) to return a list of tuples.

Python - Tuples, The differences between tuples and lists are, the tuples. To access values in tuple, use the square brackets for slicing along with the index or indices to obtain   I'm trying to obtain the n-th elements from a list of tuples. I have something like: elements = [(1,1,1),(2,3,7),(3,5,10)] I wish to extract only the second elements of each tuple into a list: seconds = [1, 3, 5] I know that it could be done with a for loop but I wanted to know if there's another way since I have thousands of tuples.

I know that it could be done with a FOR but I wanted to know if there's another way

There is another way. You can also do it with map and itemgetter:

>>> from operator import itemgetter
>>> map(itemgetter(1), elements)

This still performs a loop internally though and it is slightly slower than the list comprehension:

setup = 'elements = [(1,1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'

import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))

Results:

Method 1: 1.25699996948
Method 2: 1.46600008011

If you need to iterate over a list then using a for is fine.

Accessing nth element from Python tuples in list, A python list can contain tuples as its elements. In this article we will explore how to access every nth element form the tuples that are present  I have this list: [(hello(21,15),'now')] A tuple inside a list, and I want to extract the tuple that way the output is (hello(21,15,'now') python list python-2.7 tuples

Found this as I was searching for which way is fastest to pull the second element of a 2-tuple list. Not what I wanted but ran same test as shown with a 3rd method plus test the zip method

setup = 'elements = [(1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
method3 = 'dict(elements).values()'
method4 = 'zip(*elements)[1]'

import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup)
print('Method 3: ' + str(t.timeit(100)))
t = timeit.Timer(method4, setup)
print('Method 4: ' + str(t.timeit(100)))

Method 1: 0.618785858154
Method 2: 0.711684942245
Method 3: 0.298138141632
Method 4: 1.32586884499

So over twice as fast if you have a 2 tuple pair to just convert to a dict and take the values.

How to get the second element of a tuple in Python, A tuple is an immutable sequence of zero or more elements enclosed in parentheses. For example, the first element in ("a", 1) is "a" and the second element is 1  Python: Iterate over list of tuples; Print version number of Python module; Python: Repeat the same random numbers using seed; Python: split command line into pieces as the shell does - shlex.split() Python context tools - cwd, tmpdir; Python and PostgreSQL; RPC with Python using RPyC; Python: Fermat primality test and generating co-primes

Timings for Python 3.6 for extracting the second element from a 2-tuple list.

Also, added numpy array method, which is simpler to read (but arguably simpler than the list comprehension).

from operator import itemgetter
elements = [(1,1) for _ in range(100000)]

%timeit second = [x[1] for x in elements]
%timeit second = list(map(itemgetter(1), elements))
%timeit second = dict(elements).values()
%timeit second = list(zip(*elements))[1]
%timeit second = np.array(elements)[:,1]

and the timings:

list comprehension:  4.73 ms ± 206 µs per loop
list(map):           5.3 ms ± 167 µs per loop
dict:                2.25 ms ± 103 µs per loop
list(zip)            5.2 ms ± 252 µs per loop
numpy array:        28.7 ms ± 1.88 ms per loop

Note that map() and zip() do not return a list anymore, hence the explicit conversion.

How to get the first element of each tuple in a list in Python, Use indexing to get the first element of each tuple. Use a for-loop to iterate though a list of tuples. Within the for-loop, use the indexing syntax tuple[0] to access  A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

lists, Searches the list of tuples TupleList for a tuple whose N th element is Key . " Unzip" a list of two-tuples into two lists, where the first list contains all terms in the   Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

3. Strings, lists, and tuples, Strings, lists, and tuples are all sequence types, so called because they Last chapter you saw the len function used to get the number of characters in a string: The operator [n:m] returns the part of the sequence from the n'th element to the   How to eliminate the list of overlapping tuples for ex: samplespace = [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 2, 7), (1, 2, 8), (1, 3, 4), (1, 3, 5), (1, 3

Lists and Tuples, We use a loop to access all the elements in a list. A loop is a block for dog in dogs: The keyword "for" tells Python to get ready to use a loop. print("\nThat's just how I feel about dogs."). The list is the first mutable data type you have encountered. Once a list has been created, elements can be added, deleted, shifted, and moved around at will. Python provides a wide range of ways to modify lists. Modifying a Single List Value. A single value in a list can be replaced by indexing and simple assignment: >>>

Comments
  • and use **dict to create keyword arguments: def test(foo=3, bar=3): return foo*bar then d = {'bar': 9, 'foo'=12}; print test(**d)
  • @Wayne Werner: Yep. This stuff was all just passive knowledge (I don't often use it) - but it's good to be reminded now and then so you know where / what to look for...
  • True story - I find that in anything I use often enough (Python, vim), I tend to need reminders of neat/cool features that I've forgotten because I don't use them that often.
  • the *list syntax is pretty useful. any idea where this is described in the official python documentation?
  • I only found it in the tutorial: docs.python.org/2/tutorial/…
  • A small addition: In python-3.x the benchmark will show that map only takes a fraction of a millisecond. That's because it will return an iterator. method2 = 'list(map(itemgetter(1), elements))' renders the old behavior.
  • This is probably obvious but I would mention dict(elements).values() will result in one-element dict as opposed to list comprahension or map. This is exactly what I wanted (I was interested in unique touples) (+1 and big thanks for posting) but others might wonder why dict is faster - it's not allocating memory but only checking against existing element.
  • Consider adding some explanation.