Python3 List Operations and functions
nums = [1, 2, 3]
print(nums + [4, 5, 6])
print(nums * 3)
words = ["Python", "fun"]
index = 1
words.**insert**(index, "is")
print(words)
----------------
>>>
['Python', 'is', 'fun']
>>>
numbers = list(range(5, 20, 2))
print(numbers)
-------------------------
>>>
[5, 7, 9, 11, 13, 15, 17, 19]
>>>
nums = [55, 44, 33, 22, 11]
if all([i > 5 for i in nums]):
print("All larger than 5")
if any([i % 2 == 0 for i in nums]):
print("At least one is even")
words = ["spam", "egg", "spam", "sausage"]
print("spam" **in** words) #RETURNS TRUE
------------------------------------------
nums = [1, 2, 3]
print(**not** 4 **in** nums) #RETURNS TRUE
print(4 **not in** nums)
letters = ['p', 'q', 'r', 's', 'p', 'u']
print(letters.index('r'))
print(letters.index('z'))
----------------------------------
>>>
2
ValueError: 'z' is not in list
>>>
cubes = [i**3 for i in range(5)]
print(cubes)
>>>
[0, 1, 8, 27, 64]
>>>
A list comprehension can also contain an if statement to enforce a condition on values in the list.
evens=[i**2 for i in range(10) if i**2 % 2 == 0]
print(evens)
>>>
[0, 4, 16, 36, 64]
>>>
nums = [55, 44, 33, 22, 11]
for v in enumerate(nums):
print(v)
-------------------------
(0, 55)
(1, 44)
(2, 33)
(3, 22)
(4, 11)
nums = [1, 2, 3]
nums.**append**(4)
print(nums)
------------------------
>>>
[1, 2, 3, 4]
>>>
nums = [1, 3, 5, 2, 4]
print(len(nums))
-------------------------------
>>>
5
>>>
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(squares[2:6])
print(squares[3:8])
------------
[4, 9, 16, 25]
[9, 16, 25, 36, 49]
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(squares[::2])
print(squares[2:8:3]).
...................
>>>
[0, 4, 16, 36, 64]
[4, 25]
>>>
....................
Negative values can be used in list slicing (and normal list indexing). When negative values are used for the first and second values in a slice (or a normal index), they count from the end of the list.
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(squares[1:-1])
>>>
[1, 4, 9, 16, 25, 36, 49, 64]
>>>
If a negative value is used for the step, the slice is done backwards.
Using [::-1] as a slice is a common and idiomatic way to reverse a list.
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.