Friday, January 25, 2019

Tuple In Programming Python

In Programming Python tuple learn

Tuple in the Python programming is a form of data structure that serves to store a set of data. Tuples are immutable , meaning that the contents of the value of the tuple can not be changed and deleted. But we can fill with a variety of values and objects.

In this material, the following things will be studied:
  • How to Make a Python tuple In Program 
  • How to Access the value tuples
  • Slicing Value Tuple
  • Taking the long way tuple
  • Nested Tuple
  • Unpacking Sequence

How to Make a Python tuple In Program 

Tuple is usually made by parentheses like the following example:
t = (1234, 4321, 'Hello')
in fact it could be without brackets are like this:
t = 1234, 4321, 'World!'
Both are valid for use.

Creating Empty tuples and Singleton

If we want to create an empty tuple or no content of value, we can write the following example:
Example of Making a Tuple Blank
empty = ()
Then to make a tuple with only one (singleton), then we should be adding a comma in end code.

Example code:
# Example Make TupleSingleton 
one = ( 'contents') 
oneValue = "contents of the course",
Why should it be added in a coma?

Because if you do not add a comma, will be treated as a string.
one = ( 'content') # <- This string 
oneValue = "contents of the course" # <- This is also a string

How to Access the value tuples

Just like material lists, tuples also has an index to Access the item or value in it. The tuples index sequence and the same list that is always starting from zero 0.

Example code:
# make a tuple
name = ('Hello World', 'FajarYusuf.Com', 'linux')
# access the tuple value
print (name [1])

So the result:

In Programming Python tuple learn
If we try to change the value, then the error will occur. 
as the following example:
# make a tuple
name = ('Hello World', 'FajarYusuf.Com', 'linux')
# access the tuple value
name [1] = 'Coding'
print (name [1])

Tuple In Programming Python
Error because tuples are immutable or unchangeable value.

Slicing Value Tuple

Just like the list, tuples we can also do slicing .

Example code :
# Our prefix has this tuple
web = (123, 'FajarYusuf', '')
# then we want to cut it to be displayed
# from index numbers 1 to 2 only
print (web [1:2])

Obtained results:
Tuple In Programming Python
Slice same logic as in the list.

How to Take a Long-tuple

To take the length or number of items in tuples, how can be done by using the function len ().

Example code:
# make Tuple Day
days=('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',' Saturday ',' Sunday ')
# Take the tuple length of day
print ("Number of days:% d"% len (days))

Obtained results:
Tuple In Programming Python

Nested Tuple 

Tuple can also be nested, meaning that tuples can be filled with tuples (tuple Nested).

Example code:
tuple1 = "me", "like", "you"
tuple2 = "for", 5, "years"
tuple3 = (tuple1, tuple2) # <- nested tuple
print tuple3
tuple3 will contain the value of tuple1 and tuple2.

Tuple In Programming Python

Tuple can also be filled with any object such as a list, dictionary, object, and others.

Example :
t = ([1,2,3], {'name': 'FajarYusuf', 'rank', 123}, True)
Tuple t containing lists, dictionaries, and boolean values.

Unpacking Sequence 

Tuple making process might be called packing, while to retrieve (extract) the entire contents is called unpacking.

# Prefix create such a tuple 
web = 123,"FajarYusuf.Com","https://www.FajarYusuf.Com " 
# and in-unpacking 
id_web, name, url = web 
# then now three of these variables will be worth the 
# appropriate in the tuple 

# let us print 
print (id_web) 
print (name) 
print (url)
The result:

In Programming Python tuple learn
By doing upacking, tuple contents will be copied to the variable. Then the variables we can do anything, such as changing the contents. Because the variables are mutable.

Wednesday, January 23, 2019

Mempelajari Tuple Pada Pemrograman Python

Mempelajari Tuple Pada Pemrograman Python

Tuple pada pemrograman Python adalah bentuk stuktur data yang berfungsi untuk menyimpan sekumpulan data. Tuple bersifat immutable, artinya isi nilai pada tuple tidak bisa berubah dan dihapus. Tetapi kita dapat isi dengan berbagai macam nilai dan objek.

Pada Materi ini, hal hal berikut yang akan dipelajari :
  • Cara Membuat Tuple Pada Program Python 
  • Cara Mengakses Nilai Tuple
  • Slicing Nilai Tuple
  • Cara Mengambil panjang tuple
  • Nested Tuple
  • Unpacking Sequence

Cara Membuat Tuple Pada Program Python 

Tuple biasanya dibuat dengan tanda kurung seperti contoh berikut :
t = (1234, 4321, 'Hello')
sebenarnya bisa juga tanpa tanda kurung seperi ini :
t = 1234, 432, 'World!'
Kedua-duanya valid untuk digunakan.

Membuat Tuple Kosong dan Singleton

Apabila kita ingin membuat sebuah tuple kosong atau tanpa isi nilai, kita bisa menuliskannya seperti contoh berikut :
# contohMembuatTupleKosong
kosong = ()
Lalu untuk membuat Tuple yang hanya berisi satu (singleton), maka kita harus manambahkan tanda koma di belakangnnya.

Contoh Codingnya :
# contohMembuatTubleSingleton
satu = ('Isinya',)
isiSatu= "isinya satu saja",
Kenapa harus ditambahkan koma?

Karena kalau tidak ditambahkan koma, akan dianggap sebagai string.
satu = ('isinya') # <-- ini string
isiSatu = "isinya satu saja" # <-- ini juga string

Cara Mengakses Nilai Tuple

Sama seperti materi list, Tuple juga memiliki indeks untuk Mengakses item atau nilai yang ada di dalamnya. Urutan Indeks Tuple dan list sama yaitu selalu dimulai dari nol 0.

Contoh Codingnya:

# membuat tuple
nama = ('HelloWorld', 'FajarYusuf.Com', 'linux')
# mengakses nilai tuple

Maka hasilnya:

Mempelajari Tuple Pada Pemrograman Python

Apabila kita coba mengubah nilainya, maka akan terjadi error.
seperti contoh berikut :

# membuat tuple
nama = ('HelloWorld', 'FajarYusuf.Com', 'linux')
# mengakses nilai tuple

Hasil :
Mempelajari Tuple Pada Pemrograman Python
Erroer dikarenakan Tuple bersifat immutable atau tidak dapat diubah nilainya.

Slicing Nilai Tuple

Sama seperti list, di Tuple kita juga  bisa melakukan slicing.

Contoh Codingnya:

# awalan kita punya tuple ini
web = (123, 'FajarYusuf', '')
# lalu kita ingin potong agar ditampilkan
# dari indeks nomer 1 sampai 2 saja

Didapat hasilnya:
Mempelajari Tuple Pada Pemrograman Python

Logika slicenya sama seperti di list .

Cara Mengambil Panjang Tuple

Untuk mengambil panjang atau jumlah item di dalam Tuple, caranya bisa dilakukan dengan menggunakan fungsi len().

Contoh Codingnya :

# membuatTupleHari
hari = ('Senin', 'Selasa', 'Rabu', 'Kamis', 'Jum\'at', 'Sabtu', 'Minggu')
# Mengambil panjang tuple hari
print("Jumlah hari: %d" % len(hari))

Didapat hasilnya:
Mempelajari Tuple Pada Pemrograman Python

Nested Tuple 

Tuple juga bisa menjadi nested, artinya Tuple bisa diisi dengan Tuple(Tuple Bersarang).

Contoh Codingnya:
tuple1 = "aku", "suka", "kamu"
tuple2 = "selama", 5, "tahun"
tuple3 = (tuple1, tuple2) # <- nested tuple
print tuple3
tuple3 akan berisi nilai dari tuple1 dan tuple2.

Mempelajari Tuple Pada Pemrograman Python

Tuple juga bisa diisi dengan objek apapun seperti list, dictionary, object, dan lain-lain.

Contohnya :
t = ([1,2,3], {'nama': 'FajarYusuf', 'rank', 123}, True)
Tuple t berisi list, dictionary, dan nilai boolean.

Unpacking Sequence 

Proses pembuatan Tuble bisa kita sebut sebagai packing, sementara untuk mengambil (ekstrak) seluruh isinya disebut unpacking.

# awalan buat tuple seperti ini
web = 123, "FajarYusuf.Com", "https://www.FajarYusuf.Com"
# lalu di-unpacking
id_web, nama, url = web
# maka sekarang tiga variabel tersebut akan bernilai
# sesuai yang ada di dalam tuple
# mari kita cetak

Mempelajari Tuple Pada Pemrograman Python

Dengan melakukan upacking, isi tuple akan di-copy ke variabel. Lalu dengan variabel kita bisa melakukan apapun, seperti mengubah isinya. Karena variabel bersifat mutable.

Monday, January 21, 2019

Make a List of Data Structures Python

Make a List of Data Structures Python

How the hell do we to be able to store more data in just one variabel?

The answer is by using a List.

List is a data structure in python program that can store more than one data, as well as an array.

On this matter, we will discuss how to use the list in a Python program from the simplest example to the rather complex.

What things will we learn?
  • How to Make a List and Fill
  • How to Grep value of List
  • How Adding and Removing contents List
  • Learn Operations on List
  • and multi-dimensional List

How to Make a List in Python

List we can use as we make regular variable, but the value of the variable is filled with square brackets [] .

Example code:
# Create List empty 
color = []
# Make a list of the contents of one item 
hobby = [ "coding"]
If the list has more than one value or contents, then we can separate it with commas.

Example code:
color= ["red", "blue", "yellow", "green"]

Type any data that can be filled into this List?

list can be filled with any type of data whether it is a string, integer, float, double, boolean, object, and so on.

We can also mix in the contents.

Example code:
cupboard = [ "clothes", 25, True, 34.12]
There are four types of data in the list of the closet :
  • "Clothes" is a string data type;
  • 25 is an integer data type;
  • True is a boolean data type;
  • and 34.12 is a data type float.

How To Take Values ​​from a List

After the above material we know how to create and store a value in the List, let's try to take away its value.

As well as an array list, the list also has an index number to access the data or its contents.

color= ["red", "blue", "yellow", "green"]
  • red index to 0
  • blue index to 1
  • yellow index no.2
  • green index to 3

List the index number always starts from zero (0).

This index number that we need to take the contents (values) from the list.

Example code:
# We have a list of fruit names
food = ["rice", "meatballs", "soto", "noodles"]
# For example we want to take soto
# Then the index is 2
food print [2]
Results of the program will produce the output:

Creating a List Program

To solidify the understanding of the list in python, please try the following exercise.
  • Create a list to store the names of friends
  • Contents list of 5
  • Show the contents of the list index number 4
  • View all friends with looping
  • Show long list
Let us answer his training with the following code:
# Create a list to accommodate the names of friends
my_friends = ["Fajar", "Eka", "Andi", "Wahyu", "Nanda"]
# Display the contents of my_friends list with index number 4
print "Fill in my_friends 4th index: {}". format (my_friends [4])
# Show all friend lists
print "All friends: there are {} people". format (len (my_friends))
for friend in my_friends:
    print friend

In the above code, we use the function len () to retrieve the length of the list.

Results output:

Make a List of Data Structures Python

How to Change Values ​​List

Lists are mutable, meaning that the contents can change.

Example code:
# List first 
fruits = [ "oranges", "apples", "mango", "durian"] 
# change the index value to 3 
fruits [3] = "brown"
Then the "durian" are replaced by "sapodilla".

["oranges", "apples", "mango", "sapodilla"]

How to Add Item List

There are three methods (method) or function on a python program that can be used to add content or items to the List:
  • prepend (items) add items from the front;
  • append (item) adds an item from behind.
  • insert (index, item) adding an item of a particular index
Example code:
#list fruits
fruits= ["orange", "apple", "mango", "durian"]
# Add mangosteen
fruits.append ( "mangosteen")
The result is "mangosteen" would be added after the last item.
["orange", "apple", "mango", "durian", "mangosteen"]
The second method uses prepend ().

Methods prepend () will add an item from the front or the beginning of the list.

#list fruits
fruits=  ["orange", "apple", "mango", "durian"]
Then the "coconut" would be added at the beginning of the list.
["coconut","orange", "apple", "mango", "durian"]
Besides prepend () and append () we can use the method insert () to add the item to the index that we want.

Example code:
#list fruits
fruits= ["orange", "apple", "mango", "durian"]
fruits.insert(2, "coconut")
And the list would be like:
["orange", "apple","coconut", "mango", "durian"]

Creating a Python program with List

Now let's try to create a program by utilizing the method prepend () and append ().

Please direct typed and tested under the program coding:
# Create empty lists to accommodate hobbies
hobby = []
stop = False
i = 0
# Fill in a hobby
while (not stop):
    new_hobby = raw_input ("Input hobby that is {}:". format (i))
    hobby.append (new_hobby)
    # Increment i
    i += 1
    ask = raw_input ("Want to fill again? (y/n):")
    if (ask == "n"):
        stop = True
# Print All Hobbies
print "=" * 10
print "You have {} hobby". format (len(hobby))
for hb in hobby:
    print "- {}". format (hb)

Try execution and fed a hobby you want value then the result will be like this:

Make a List of Data Structures Python

How to Delete Items in List

To remove one of the values ​​of the List, we can use the command del.

Del command will erase the memory of a value of the variable.

Example code:
# Make a List
todo_list = [
    "Learning Python",
    "Learning PHP",
    "Learning HTML",
    "Learning CSS",
    "Learning JAVA"
# Suppose we want to delete "Learning CSS"
# which is in the 3rd index
del todo_list [3]
print todo_list

As a result, "Learning CSS" will be deleted:

Make a List of Data Structures Python

In addition to using the command del, we also can use the method remove () with a parameter value to be deleted.

Example code:
# letter list
letters = ["a", "b", "c", "d"]
# then we delete c
letters.remove ("c")
print letters

The result:

Make a List of Data Structures Python

cutting list

Like the string data type, the list can also be cut into pieces.

Example code:
# We have a list of colors 
colors = [ "red", "green", "yellow", "blue", "pink", "purple"] 
# We cut from the index to the 1st until the 5th 
print color [1: 5 ]
The result is an index of 0 [red] and 6 [purple] will not be displayed:
[ 'green', 'yellow', 'blue', 'pink']

Use Operations List

There are some operations that can be performed on the List, including:

  • Merger (+)
  • Multiplication (*)
Example code:
# List of songs 
list_song= [ 
    "The Beginning", 
    "Dear God" 

# list of favorite songs 
playlist_favorite = [ 
    "Break Out", 
    "Now Loading !!!" 

# Let us combine both 
all_song = all_song + playlist_favorite 
print all_song 
The result:
['The Beginning, No Cry', 'Dear God', 'Break Out', 'Now Loading!!!']
As for the multiplication operation can only be performed with a value that is a number.

Example code:

# List of song
playlist_favorite = [
    "The Beginning",
    "Now Loading!!!"
# repeat 5 times
repeat = 5
now_playing = playlist_favorite * repeat 
print now_playing
The result:
['The Beginning', 'Now Loading!!!', 'The Beginning', 'Now Loading!!!', 'The Beginning', 'Now Loading!!!', 'The Beginning', 'Now Loading!!!', 'The Beginning', 'Now Loading!!!']

List Multi Dimensions

In the above material, we just make the program one-dimensional list.

List can also have more than one dimension, or so-called multi-dimensional.

Multi-dimensional list is usually used to store complex data structures such as tables, matrices, graphs, tree, etc.

Example code:
# List of drinks with a 2 dimensional 
list_drinks = [ 
    [ "coffee", "Milk", "tea"], 
    [ "Apple Juice", "Juice Melon", "Orange Juice"], 
    [ "Ice Milk", "Ice Mixed" "Ice Teler"] 

# How to access the list of multidimensional 
# suppose we want to take the "Ice Milk" 
print list_drinks [2] [0]

Dyad 2 in the above code, attribute index will we access list. Then after to list its new take its contents.

Results output:
"Ice Milk"
What if we want to display all contents in a multi-dimensional list above?

Here's how, Try using nested loops.
# 2-dimensional drink list
list_drinks = [
    ["Coffee", "Milk", "Sweet Tea"],
    ["Apple Juice", "Melon Juice", "Orange Juice"],
    ["Milk Ice", "Ice Mix", "Ice Teler"]
for menu in list_drinks :
    for drinks in menu:
        print drinks 
The result:
Sweet Tea 
Apple Juice 
Melon Juice 
Orange Juice 
Ice Milk 
Ice Mix
Ice Teler