python data collection type

artem-sapegin-176819-unsplash

Data Collection Types

List is a collection which is ordered and changeable. Allows duplicate members.

  • Written with square brackets []
  • can access the list items by referring to the index number [0,1,2, etc]
  • use len() to find out how many elements are in the list
  • use listname.append() to add new values
  • use listname.insert(index, “value”) to insert a new item in a specific position
  • use listname.remove(“value”) to remove a specified value
  • use listname.pop(index) to remove a value from specific index position ; if not specified, it takes the last value
  • use listname.clear() to empty the list
  • use listname.sort() to sort the list

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

  • written with round brackets ()
  • can access tuple items with index numbers
  • use len() to find out how many elements are in the tuple
  • use del tuplename if you want to delete the tuple completely, but cannot be modified like the list above

Set is a collection which is unordered and unindexed. No duplicate members.

  • written with curly brackets {}
  • cannot change items but can add new items within the set
  • use setname.add() to add one additional item to the set
  • use setname.update() to add multiple items within the set
  • use setname.remove(“value”) to remove a value / outputs an error if the value is not within the set
  • setname.discard(“value”) also removes but does not give an error if the value is not in the set
  • use setname.clear() to empty the set
  • use del setname to delete it completely

Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

  • written with curly brackets {} with key and value
  • use dictname.value(key) to get value associated with the keyuse for x in thisdict.values(): // print(x) to see all values in the dictionary
  • use for x, y in thisdict.items():
  • print(x, y) to loop through all keys and values
  • use dictname.add[“key”] = “value” to add new k & v
  • use dictnaame.pop(“key”) to remove both k & v
  • use dictname.popitem() to remove the last k & v
  • use del dictname[“key”] to remove both k & v
  • use del dictname to completely delete
  • use dictname.clear() to empty

Photo by Artem Sapegin on Unsplash

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s