Python Part4: For loop, argument passing and Tuple
For loop
- items = [a, b, c, d]
- for item in items:
- for i in range(5)
Argument passing
- Function with arguments.
- def modify(k)
- m = [6, 7, 8, 9]
- modify(m)
- Default arguments.
- def DisplayMessage(m='nothing')
- message = 'Welcome to python'
- DisplayMessage(Message)
- DisplayMessage()
Tuple
- Heterogeneous immutable collection.
- Delimited by parentheses.
- For example t = ("norway", 4.953, 3)
- Items separated by commas.
- Element access with square brackets and zero-based index. T[index]
- len(t) for number of elements.
-
Iteration with for loop.
- for item in t:
- print(item)
- Concatenation with + operator.
- t + (338186.0, 2659)
- ('Norway', 4.953, 3, 338186.0, 2659)
- Reputation with * operator.
- t * 3
- ('Norway', 4.953, 3, 'Norway', 4.953, 3, 'Norway', 4.953, 3)
-
Tuple can contain any kind of object.
- Nested tuples.
- A = ((245, 446), (90, 456))
- Chain square-brackets indexing to access inner elements.
- Can’t use one object in parentheses as a single element tuple.
- For a single element tuple include a trailing comma.
- The empty tuple is simply empty parentheses.
-
Delimiting parentheses are optional for one or more elements.
- p = 1, 1, 1, 4, 6, 19
- >>> p
- (1, 1, 1, 4, 6, 19)
- Tuples are useful for multiple return values.
- def MinMax(items)
- Return Min(items), Max(items)
- >>> MinMax([33, 30, 9, 82, 87])
- (9, 87)
-
Tuple unpacking allow us to destructure directly into named references.
- lower, upper = MinMax([33, 30, 9, 82, 87])
- >>> lower
- 9
- >>> upper
- 87
- Tuple unpacking works with arbitrarily nested tuples (although not with other data structure)
- (a, (b, (c, d))) = (4, (3, (2, 1)))
- >>> a
- 4
- >>> b
- 3
- >>> c
- 2
- >>> d
- 1
- a, b = b, a is the idiomatic python swap.
-
Use the tuple constructor to create tuples from other iterable series of objects.
- >>> tuple([234, 444, 897])
- (234, 444, 897)
- >>> tuple("car")
- ('c', 'a', 'r')
- The in and not in operators can be used with tuples - and other collection types – for membership testing.
- >>> 5 in (3, 5, 9, 13)
- True
- >>> 5 not in (3, 5, 9, 13)
- False
See Also
No comments:
Post a Comment