How to find the last element of list in Python assume sam is the name of list

Python | How to get the last element of list

List, being an essential python container is used in day-day programming and also in web-development. Knowledge of its operations is necessary.

Let’s see all the different ways of accessing the last element of a list.

Method #1 : Naive Method

There can be 2-naive methods to get the last element of the list.

  • Iterating the whole list and getting, the second last element.
  • Reversing the list and printing the first element.




# Python 3 code to demonstrate
# accessing last element of list
# using naive method
# initializing list
test_list = [1, 4, 5, 6, 3, 5]
# printing original list
print ("The original list is : " + str(test_list))
# First naive method
# using loop method to print last element
for i in range(0, len(test_list)):
if i == (len(test_list)-1):
print ("The last element of list using loop : "
+ str(test_list[i]))
# Second naive method
# using reverse method to print last element
test_list.reverse()
print("The last element of list using reverse : "
+ str(test_list[0]))

Output :



The original list is : [1, 4, 5, 6, 3, 5] The last element of list using loop : 5 The last element of list using reverse : 5


Method #2 : Using [] operator

The last element can be assessed easily if no. of elements in list are already known. There are 2 index in Python that point to last element in list.

  • list[ len - 1 ] : Points to last element by definition.
  • list[-1] : In python, negative indexing starts from end.




# Python3 code to demonstrate
# accessing last element of list
# using [] operator
# initializing list
test_list = [1, 4, 5, 6, 3, 5]
# printing original list
print ("The original list is : " + str(test_list))
# using len - 1 index to print last list element
print ("The last element using [ len -1 ] is : "
+ str(test_list[len(test_list) -1]))
# using -1 index to print last list element
print ("The last element using [ -1 ] is : "
+ str(test_list[-1]))

Output :

The original list is : [1, 4, 5, 6, 3, 5] The last element using [ len -1 ] is : 5 The last element using [ -1 ] is : 5


Method #3 : Using list.pop()

The list.pop() method is used to access the last element of the list. The drawback of this approach is that it also deletes the list last element, hence is only encouraged to use when list is not to be reused.




# Python3 code to demonstrate
# accessing last element of list
# using list.pop()
# initializing list
test_list = [1, 4, 5, 6, 3, 5]
# printing original list
print ("The original list is : " + str(test_list))
# using pop() to print last list element
print ("The last element using pop() is : "
+ str(test_list.pop()))

Output :

The original list is : [1, 4, 5, 6, 3, 5] The last element using pop() is : 5


Method #4 : Using reversed() + next()

reversed() coupled with next() can easily be used to get the last element, as like one of the naive method, reversed method returns the reversed ordering of list as an iterator, and next() method prints the next element, in this case last element.




# Python3 code to demonstrate
# accessing last element of list
# using reversed() + next()
# initializing list
test_list = [1, 4, 5, 6, 3, 5]
# printing original list
print ("The original list is : " + str(test_list))
# using reversed() + next() to print last element
print ("The last element using reversed() + next() is : "
+ str(next(reversed(test_list))))

Output :

The original list is : [1, 4, 5, 6, 3, 5] The last element using reversed() + next() is : 5

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python list-programs
python-list
Practice Tags :
python-list
Read Full Article

In Python, how do you get the last element of a list?

To just get the last element,

  • without modifying the list, and
  • assuming you know the list has a last element (i.e. it is nonempty)

pass -1 to the subscript notation:

>>> a_list = ['zero', 'one', 'two', 'three'] >>> a_list[-1] 'three'

How to get the last element of a list in Python?

PythonServer Side ProgrammingProgramming

Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want last element in list, use -1 as index.

>>> L1=[1,2,3,4,5] >>> print (L1[-1]) 5
Malhar Lathkar
Published on 12-Jan-2018 19:20:43
Previous Page Print Page
Next Page
Advertisements

Get last item of a list using negative indexing

List in python supports negative indexing. So, if we have a list of size “S”, then to access the Nth element from last we can use the index “-N”. Let’s understand by an example,
Suppose we have a list of size 10,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
To access the last element i.e. element at index 9 we can use the index -1,
# Get last element by accessing element at index -1 last_elem = sample_list[-1] print('Last Element: ', last_elem)
Output:
Last Element: 9
Similarly, to access the second last element i.e. at index 8 we can use the index -2.
last_elem = sample_list[-2]
Output:
Last Element: 8
Using negative indexing, you can select elements from the end of list, it is a very efficient solution even if you list is of very large size. Also, this is the most simplest and most used solution to get the last element of list. Let’s discuss some other ways,

Overview — Creating a List in Python

There are many ways of creating a list in Python. Let’s get a quick overview in the following table:

CodeDescription
[]Square bracket: Initializes an empty list with zero elements. You can add elements later.
[x1, x2, x3, … ]List display: Initializes an empty list with elements x1, x2, x3, … For example, [1, 2, 3] creates a list with three integers 1, 2, and 3.
[expr1, expr2, ... ]List display with expressions: Initializes a list with the result of the expressions expr1, expr2, … For example, [1+1, 2-1] creates the list [2, 1].
[expr for var in iter]List comprehension: applies the expression expr to each element in an iterable.
list(iterable)List constructor that takes an iterable as input and returns a new list.

You can play with some examples in our interactive Python shell:

Exercise: Use list comprehension to create a list of square numbers.

Introduction¶

Pysam is a python module that makes it easy to read and manipulate mapped short read sequence data stored in SAM/BAM files. It is a lightweight wrapper of the htslib C-API.

This page provides a quick introduction in using pysam followed by the API. See Working with BAM/CRAM/SAM-formatted files for more detailed usage instructions.

To use the module to read a file in BAM format, create a AlignmentFile object:

import pysam samfile = pysam.AlignmentFile("ex1.bam", "rb")

Once a file is opened you can iterate over all of the read mapping to a specified region using fetch(). Each iteration returns a AlignedSegment object which represents a single read along with its fields and optional tags:

for read in samfile.fetch('chr1', 100, 120): print(read) samfile.close()

To give:

EAS56_57:6:190:289:82 0 99 <<<7<<<;<<<<<<<<8;;<7;4<;<;;;;;94<; 69 CTCAAGGTTGTTGCAAGGGGGTCTATGTGAACAAA 0 192 1 EAS56_57:6:190:289:82 0 99 <<<<<<;<<<<<<<<<<;<<;<<<<;8<6;9;;2; 137 AGGGGTGCAGAGCCGAGTCACGGGGTTGCCAGCAC 73 64 1 EAS51_64:3:190:727:308 0 102 <<<<<<<<<<<<<<<<<<<<<<<<<<<::<<<844 99 GGTGCAGAGCCGAGTCACGGGGTTGCCAGCACAGG 99 18 1 ...

You can also write to a AlignmentFile:

import pysam samfile = pysam.AlignmentFile("ex1.bam", "rb") pairedreads = pysam.AlignmentFile("allpaired.bam", "wb", template=samfile) for read in samfile.fetch(): if read.is_paired: pairedreads.write(read) pairedreads.close() samfile.close()

An alternative way of accessing the data in a SAM file is by iterating over each base of a specified region using the pileup() method. Each iteration returns a PileupColumn which represents all the reads in the SAM file that map to a single base in the reference sequence. The list of reads are represented as PileupRead objects in the PileupColumn.pileups property:

import pysam samfile = pysam.AlignmentFile("ex1.bam", "rb" ) for pileupcolumn in samfile.pileup("chr1", 100, 120): print("\ncoverage at base %s = %s" % (pileupcolumn.pos, pileupcolumn.n)) for pileupread in pileupcolumn.pileups: if not pileupread.is_del and not pileupread.is_refskip: # query position is None if is_del or is_refskip is set. print('\tbase in read %s = %s' % (pileupread.alignment.query_name, pileupread.alignment.query_sequence[pileupread.query_position])) samfile.close()

The above code outputs:

coverage at base 99 = 1 base in read EAS56_57:6:190:289:82 = A coverage at base 100 = 1 base in read EAS56_57:6:190:289:82 = G coverage at base 101 = 1 base in read EAS56_57:6:190:289:82 = G coverage at base 102 = 2 base in read EAS56_57:6:190:289:82 = G base in read EAS51_64:3:190:727:308 = G ...

Commands available in csamtools are available as simple function calls. For example:

pysam.sort("-o", "output.bam", "ex1.bam")

corresponds to the command line:

samtools sort -o output.bam ex1.bam

Analogous to AlignmentFile, a TabixFile allows fast random access to compressed and tabix indexed tab-separated file formats with genomic data:

import pysam tabixfile = pysam.TabixFile("example.gtf.gz") for gtf in tabixfile.fetch("chr1", 1000, 2000): print(gtf.contig, gtf.start, gtf.end, gtf.gene_id)

TabixFile implements lazy parsing in order to iterate over large tables efficiently.

More detailed usage instructions is at Working with BAM/CRAM/SAM-formatted files.

Note

Coordinates in pysam are always 0-based (following the python convention). SAM text files use 1-based coordinates.

Note

The above examples can be run in the tests directory of theinstallation directory. Type ‘make’ before running them.

See also

//github.com/pysam-developers/pysam

The pysam code repository, containing source code and download instructions

//pysam.readthedocs.org/en/latest/

The pysam website containing documentation

Video liên quan

Postingan terbaru

LIHAT SEMUA