Home arrow Python arrow Page 3 - Python 101 (part 4): Feeding The Snake

Strange Food - Python

Luke Skywalker has the Force. Python programmers havedictionaries and tuples. What's the connection? Read on to find out...

TABLE OF CONTENTS:
  1. Python 101 (part 4): Feeding The Snake
  2. Running The Lights
  3. Strange Food
  4. Unbreakable
  5. Looking Up The Dictionary
  6. Of Keys And Locks
By: Vikram Vaswani, (c) Melonfire
Rating: starstarstarstarstar / 8
June 25, 2001

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
Tuples can be concatenated with the + operator,

>>> CreepyCrawlies ('spiders', 'ants', 'lizards') >>> pasta ('macaroni', 'spaghetti', 'lasagne', 'fettucine') >>> strangeFood = CreepyCrawlies + pasta >>> strangeFood ('spiders', 'ants', 'lizards', 'macaroni', 'spaghetti', 'lasagne', 'fettucine') >>>
and repeated with the * operator.

>>> pasta * 5 ('macaroni', 'spaghetti', 'lasagne', 'fettucine', 'macaroni', 'spaghetti', 'lasagne', 'fettucine', 'macaroni', 'spaghetti', 'lasagne', 'fettucine', 'macaroni', 'spaghetti', 'lasagne', 'fettucine', 'macaroni', 'spaghetti', 'lasagne', 'fettucine') >>>
"Slices" of a tuple can be extracted using notation similar to that used with lists - take a look:

>>> pasta = ("macaroni", "spaghetti", "lasagne", "fettucine", "tagliatelle", "rigatoni") >>> pasta[0] 'macaroni' >>> pasta[2:] ('lasagne', 'fettucine', 'tagliatelle', 'rigatoni') >>> pasta[1:3] ('spaghetti', 'lasagne') >>> pasta[:4] ('macaroni', 'spaghetti', 'lasagne', 'fettucine') >>> pasta[-4] 'lasagne' >>> pasta[-1] 'rigatoni' >>>
The built-in len() function can be used to calculate the number of elements in a tuple,

>>> pasta ('macaroni', 'spaghetti', 'lasagne', 'fettucine', 'tagliatelle', 'rigatoni') >>> len(pasta) 6 >>>
while the "in" and "not in" operators can be used to test for the presence of a particular element in a tuple. A match returns 1 (true), while a failure returns 0 (false).

>>> pasta ('macaroni', 'spaghetti', 'lasagne', 'fettucine', 'tagliatelle', 'rigatoni') >>> "macaroni" in pasta 1 >>> "ravioli" in pasta 0 >>> "ravioli" not in pasta 1 >>> "ravio" not in pasta 1 >>> "maca" in pasta 0 >>>


 
 
>>> More Python Articles          >>> More By Vikram Vaswani, (c) Melonfire
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: