Created
March 7, 2016 15:38
-
-
Save thigm85/eea2aafa883ac877b91a to your computer and use it in GitHub Desktop.
Code sample for working with lists in python. Reference: https://docs.python.org/2/tutorial/introduction.html#lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # create a list | |
| squares = [1, 4, 9, 16, 25] | |
| # indexing | |
| squares[0] # it is zero-based index | |
| squares[-1] | |
| # slicing | |
| squares[0:2] # [inclusive, exclusive], first and second element | |
| squares[-2:] # last two elements | |
| # Create a shallow copy of a list object | |
| squares[:] # Check (https://docs.python.org/2/library/copy.html) | |
| # concatenation | |
| squares + [36, 49, 64, 81, 100] | |
| # lists are mutable | |
| cubes = [1, 8, 27, 65, 125] # something's wrong here | |
| cubes[3] = 64 # replace the wrong value | |
| # append values at the end | |
| cubes.append(216) | |
| # assignments to slices | |
| letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] | |
| letters[2:5] = ['C', 'D', 'E'] # replace some values | |
| letters[2:5] = [] # now remove them | |
| letters[:] = [] # clear the list by replacing all the elements with an empty list | |
| # compute the size of a list | |
| len(squares) | |
| # nested lists | |
| a = ['a', 'b', 'c'] | |
| n = [1, 2, 3] | |
| x = [a, n] # [['a', 'b', 'c'], [1, 2, 3]] | |
| x[0] # ['a', 'b', 'c'] | |
| x[0][1] # 'b' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment