Pages

Python Collections Data Types

There are four collection data types in the Python programming language:
  • Lists
  • Tuple
  • Set
  • Dictionary

List is a collection which is ordered and changeable. Allows duplicate members.Lists are very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. 

Lists can also be iterated over in a very simple manner. Here is an example of how to build a list.Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets.
Python lists are written with square brackets.

<code class="css">
Example:
//Comments

myist = ["car", "bike", "train"]
print(myist)
Output:
/Users/gowthamrajamanickam/PycharmProjects/PNPDemo/venv/bin/python /Users/gowthamrajamanickam/PycharmProjects/PNPDemo/PythonDemo.py
['car', 'bike', ‘train']


</code>
You access the list items by referring to the index number,

Example
myist = ["car", "bike", "train"]
print(myist[2])

Output

/Users/gowthamrajamanickam/PycharmProjects/PNPDemo/venv/bin/python /Users/gowthamrajamanickam/PycharmProjects/PNPDemo/PythonDemo.py
train


You can loop through the list items by using a for loop:
myist = ["car", "bike", "train"]
for x in myist:
  print(x)


Output

/Users/gowthamrajamanickam/PycharmProjects/PNPDemo/venv/bin/python /Users/gowthamrajamanickam/PycharmProjects/PNPDemo/PythonDemo.py
car
bike
train
To add an item to the end of the list, use the append() method:
Example


myist = ["car", "bike", "train"]
myist.append("Bus")
for x in myist:
  print(x)

Output
/Users/gowthamrajamanickam/PycharmProjects/PNPDemo/venv/bin/python /Users/gowthamrajamanickam/PycharmProjects/PNPDemo/PythonDemo.py
car
bike
train
Bus



Gowtham

Phasellus facilisis convallis metus, ut imperdiet augue auctor nec. Duis at velit id augue lobortis porta. Sed varius, enim accumsan aliquam tincidunt, tortor urna vulputate quam, eget finibus urna est in augue.

No comments:

Post a Comment