Python Slicing & iterating

Source: Internet
Author: User
Tags iterable


Python provides the slice (Slice) operator
L = [' Michael ', ' Sarah ', ' Tracy ', ' Bob ', ' Jack ']
Take first 3 elements
>>> L[0:3]
[' Michael ', ' Sarah ', ' Tracy ']
L[0:3] Indicates that the fetch starts at index 0 until index 3, but does not include index 3. That is, index 0,1,2

you can also start with index 1 and take out 2 elements:
>>> L[1:3]
Python supports l[-1] to take the first element of the countdown, it also supports the inverse slice
>>> l[-2:]
[' Bob ', ' Jack ']
>>> L[-2:-1]
[' Bob ']
Create a sequence of 0-99:
>>> L = list (range)
first 10 numbers, each of two fetch one:
>>> L[:10:2]
[0, 2, 4, 6, 8]

A string can also be seen as a list, with each element being a character. Therefore, strings can also be manipulated with slices
>>> ' ABCDEFG ' [: 3]
' ABC '
>>> ' ABCDEFG ' [:: 2]
' Aceg '

iteration
By default, the Dict iteration is key. If you want to iterate over value, you can use for value in D.values (), if you want to iterate both key and value at the same time, you can use for K, V in D.items ()
>>> d = {' A ': 1, ' B ': 2, ' C ': 3}
>>> for key in D:
... Print (key)
...
a
c
b

>>> for ch in ' ABC ':
... print (CH)
...
a
b
c
python the built-in enumerate function can turn a list into an index-element pair, This allows you to iterate both the index and the element itself in the FOR loop:

>>> for I, value in enumerate ([' A ', ' B ', ' C '):

...
0 A
1 B
2 C

>>> from collections Import iterable
>>> isinstance (' abc ', iterable) # whether STR can iterate
True

Any iterator object can be used for a for loop, including our custom data types, and can be used for loops as long as the iteration criteria are met.

Python Slicing & iterating

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.