Laravel 8 Roles and Permissions Without Package

https://www.codecheef.org/user/img/fevicon.png

Laravel 8 Roles and Permissions Without Package

Posted By


Mahedi Hasan

Category

Framework

Sub-category

Laravel 5.6

November 14, 2019

Roles and permissions are an important part of many web applications. In this tutorial we will see how we can implement user roles and permissions system in laravel. We will see it from scratch. We won’t use /laravel-permission package for doing it. But you can use /laravel-permission to create this roles and permissions system in laravel 8.

It is important to add laravel user roles and permissions mechanism in our large scale application to give the permit to user to specific task. We will see from scratch laravel 8 user roles and permissions tutorial. 

If you don’t know how to create laravel 8 roles and permissions, then you are a right place. I will teach you from scratch laravel roles and permissions.But in this tutorial we will do user roles and permissions in laravel using our own custom code. So let’s start how to implement & setup roles and permissions in Laravel.

I updated this tutorial for laravel 8 version. So if you face any error, then you can check git repository. Let’s start laravel 8 user roles and permissions tutorial.

 

Git Repository : User Roles & Access Permission Laravel 

 

roles-permissions-laravel

 

Step 1 : Download Laravel Project

Open up your terminal and create a new Laravel project by typing in the following command

composer create-project --prefer-dist laravel/laravel blog

 

Step 2:  Make Auth

If you are using laravel version 6 then run below command to make auth

composer require laravel/ui --dev
php artisan ui vue --auth
npm install
npm run watch

 

If you are using below laravel version 6 then run below command to make auth

php artisan make:auth

 

Step 3 : Make Model

We need model to make users roles and permissions. So let’s create our model using below command.

php artisan make:model Permission -m
php artisan make:model Role -m

 

As you may know, -m flag will create a migration file for the model. Now you’ll have two new migration files waiting for you to add new fields. 

 

Step 4 : Edit the migration file

 

public function up()
    {
       Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email',191)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
    });
}

 

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePermissionsTable extends Migration
{
    
    public function up()
    {
        Schema::create('permissions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name'); // edit posts
            $table->string('slug'); //edit-posts
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('permissions');
    }
}

 

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRolesTable extends Migration
{
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name'); // edit posts
            $table->string('slug'); //edit-posts
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

 

Step 5 : Adding pivot tables

For this first pivot table, we’ll create a new migration file for the table users_permissions. So run below command to create

php artisan make:migration create_users_permissions_table --create=users_permissions

 

For this pivot table between users and permissions, our schema should look like

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersPermissionsTable extends Migration
{
    public function up()
    {
        Schema::create('users_permissions', function (Blueprint $table) {
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('permission_id');

            //FOREIGN KEY CONSTRAINTS
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
 
            //SETTING THE PRIMARY KEYS
            $table->primary(['user_id','permission_id']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('users_permissions');
    }
}

 

Now let’s create a pivot table for users_roles.

php artisan make:migration create_users_roles_table --create=users_roles

 

The fields inside this table will pretty much the same as in users_permissions table. Our schema for this table will look like:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersRolesTable extends Migration
{
    public function up()
    {
        Schema::create('users_roles', function (Blueprint $table) {
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('role_id');

         //FOREIGN KEY CONSTRAINTS
           $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
           $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

         //SETTING THE PRIMARY KEYS
           $table->primary(['user_id','role_id']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('users_roles');
    }
}

 

Under a particular Role, User may have specific Permission

For example, a user may have the permission for post a topic, and an admin may have the permission to edit or delete a topic. In this case, let’s setup a new table for roles_permissions to handle this complexity.

 

php artisan make:migration create_roles_permissions_table --create=roles_permissions

 

The Schema will be like:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRolesPermissionsTable extends Migration
{
    public function up()
    {
        Schema::create('roles_permissions', function (Blueprint $table) {
             $table->unsignedInteger('role_id');
             $table->unsignedInteger('permission_id');

             //FOREIGN KEY CONSTRAINTS
             $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
             $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');

             //SETTING THE PRIMARY KEYS
             $table->primary(['role_id','permission_id']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('roles_permissions');
    }
}

 

Now run following command to create migration

php artisan migrate

 

Step 6 : Setting up the relationships

We’ll start by creating the relationships between roles and permissions table. In our Role.php , Permision.php.

App/Role.php

public function permissions() {

   return $this->belongsToMany(Permission::class,'roles_permissions');
       
}

public function users() {

   return $this->belongsToMany(User::class,'users_roles');
       
}

 

App/Permission.php

public function roles() {

   return $this->belongsToMany(Role::class,'roles_permissions');
       
}

public function users() {

   return $this->belongsToMany(User::class,'users_permissions');
       
}

 

Step 7 : Creating a Trait

Inside of our app directory, let’s create a new directory and name it as Permissions and create a new file namely HasPermissionsTrait.php. A nice little trait has been setup to handle user relations. Back in our User model, just import this trait and we’re good to go.

app/User.php

namespace App;

use App\Permissions\HasPermissionsTrait;

class User extends Authenticatable
{
    use HasPermissionsTrait; //Import The Trait
}

 

Now open HasPermissionsTrait.php and paste those following code.

App/Permissions/HasPermissionsTrait.php

namespace App\Permissions;

use App\Permission;
use App\Role;

trait HasPermissionsTrait {

   public function givePermissionsTo(... $permissions) {

    $permissions = $this->getAllPermissions($permissions);
    dd($permissions);
    if($permissions === null) {
      return $this;
    }
    $this->permissions()->saveMany($permissions);
    return $this;
  }

  public function withdrawPermissionsTo( ... $permissions ) {

    $permissions = $this->getAllPermissions($permissions);
    $this->permissions()->detach($permissions);
    return $this;

  }

  public function refreshPermissions( ... $permissions ) {

    $this->permissions()->detach();
    return $this->givePermissionsTo($permissions);
  }

  public function hasPermissionTo($permission) {

    return $this->hasPermissionThroughRole($permission) || $this->hasPermission($permission);
  }

  public function hasPermissionThroughRole($permission) {

    foreach ($permission->roles as $role){
      if($this->roles->contains($role)) {
        return true;
      }
    }
    return false;
  }

  public function hasRole( ... $roles ) {

    foreach ($roles as $role) {
      if ($this->roles->contains('slug', $role)) {
        return true;
      }
    }
    return false;
  }

  public function roles() {

    return $this->belongsToMany(Role::class,'users_roles');

  }
  public function permissions() {

    return $this->belongsToMany(Permission::class,'users_permissions');

  }
  protected function hasPermission($permission) {

    return (bool) $this->permissions->where('slug', $permission->slug)->count();
  }

  protected function getAllPermissions(array $permissions) {

    return Permission::whereIn('slug',$permissions)->get();
    
  }

}

 

Here, we’re iterating through the roles and checking by the slug field, if that specific role exists. You can check or debug this by using:

$user = $request->user(); //getting the current logged in user
dd($user->hasRole('admin','editor')); // and so on

 

Step 8 :  Create CustomProvider

We’ll be utilizing the Laravel’s “can” directive to check if the User have Permission. and instead of using $user->hasPermissionTo().

we’ll use $user->can() To do so, we need to create a new PermissionsServiceProvider for authorization

php artisan make:provider PermissionsServiceProvider

 

Register your service provider and head over to the boot method to provide us a Gateway to use can() method.

namespace App\Providers;

use App\Permission;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class PermissionsServiceProvider extends ServiceProvider
{
   
    public function register()
    {
        //
    }

    public function boot()
    {
        try {
            Permission::get()->map(function ($permission) {
                Gate::define($permission->slug, function ($user) use ($permission) {
                    return $user->hasPermissionTo($permission);
                });
            });
        } catch (\Exception $e) {
            report($e);
            return false;
        }

        //Blade directives
        Blade::directive('role', function ($role) {
             return "if(auth()->check() && auth()->user()->hasRole({$role})) :"; //return this if statement inside php tag
        });

        Blade::directive('endrole', function ($role) {
             return "endif;"; //return this endif statement inside php tag
        });

    }
}

 

now we have to register our PermissionsServiceProvider. Open this following file add this in providers array.

config\app.php

 'providers' => [

        App\Providers\PermissionsServiceProvider::class,
    
 ],

 

You can learn more about Laravel’s Gate facade at Laravel’s documentation. You can test it out as:

dd($user->can('permission-slug'));

 

Read also :  Laravel 6 Authorization using Gates

 

Step 9 : Add Dummy Data To Check

For creating roles and permissions tutorial, we need dummy data to check our user access. To create it paste this following code into this followng slug.

Route::get('/roles', 'PermissionController@Permission');

 

App\Http\Controllers\PermissionController.php

namespace App\Http\Controllers;

use App\Permission;
use App\Role;
use App\User;
use Illuminate\Http\Request;

class PermissionController extends Controller
{   

    public function Permission()
    {   
    	$dev_permission = Permission::where('slug','create-tasks')->first();
		$manager_permission = Permission::where('slug', 'edit-users')->first();

		//RoleTableSeeder.php
		$dev_role = new Role();
		$dev_role->slug = 'developer';
		$dev_role->name = 'Front-end Developer';
		$dev_role->save();
		$dev_role->permissions()->attach($dev_permission);

		$manager_role = new Role();
		$manager_role->slug = 'manager';
		$manager_role->name = 'Assistant Manager';
		$manager_role->save();
		$manager_role->permissions()->attach($manager_permission);

		$dev_role = Role::where('slug','developer')->first();
		$manager_role = Role::where('slug', 'manager')->first();

		$createTasks = new Permission();
		$createTasks->slug = 'create-tasks';
		$createTasks->name = 'Create Tasks';
		$createTasks->save();
		$createTasks->roles()->attach($dev_role);

		$editUsers = new Permission();
		$editUsers->slug = 'edit-users';
		$editUsers->name = 'Edit Users';
		$editUsers->save();
		$editUsers->roles()->attach($manager_role);

		$dev_role = Role::where('slug','developer')->first();
		$manager_role = Role::where('slug', 'manager')->first();
		$dev_perm = Permission::where('slug','create-tasks')->first();
		$manager_perm = Permission::where('slug','edit-users')->first();

		$developer = new User();
		$developer->name = 'Mahedi Hasan';
		$developer->email = 'mahedi@gmail.com';
		$developer->password = bcrypt('secrettt');
		$developer->save();
		$developer->roles()->attach($dev_role);
		$developer->permissions()->attach($dev_perm);

		$manager = new User();
		$manager->name = 'Hafizul Islam';
		$manager->email = 'hafiz@gmail.com';
		$manager->password = bcrypt('secrettt');
		$manager->save();
		$manager->roles()->attach($manager_role);
		$manager->permissions()->attach($manager_perm);

		
		return redirect()->back();
    }
}

 

Now goto this url and hit enter on your keyboard. Then you will see some dummy data to those following tables. To test this out in your routes files, we can die and dump on:

$user = $request->user();
dd($user->hasRole('developer')); //will return true, if user has role
dd($user->givePermissionsTo('create-tasks'));// will return permission, if not null
dd($user->can('create-tasks')); // will return true, if user has permission

 

Inside of our view files, we can use it like:

@role('developer')

 Hello developer

@endrole

 

This means only those user can see it whose role are developer. Now you can use many role as you want.

 

Step 10 : Setup the Middleware

 

Read also : How to Create Middleware with Parameters in Laravel 6

 

In order to protect our routes, we can setup the middleware to do so.

php artisan make:middleware RoleMiddleware

 

Add the middleware into your kernel & setup the handle method as follows

App\Http\Middleware\RoleMiddleware.php

namespace App\Http\Middleware;

use Closure;

class RoleMiddleware
{

    public function handle($request, Closure $next, $role, $permission = null)
    {
        if(!$request->user()->hasRole($role)) {

             abort(404);

        }

        if($permission !== null && !$request->user()->can($permission)) {

              abort(404);
        }

        return $next($request);

    }
}

 

Now we have to register this RoleMiddleware. So add this following code to register it.

App\Http\Kernel.php

protected $routeMiddleware = [
    .
    .
    'role' => \App\Http\Middleware\RoleMiddleware::class,
];

 

Right now in our routes, we can do something like this

Route::group(['middleware' => 'role:developer'], function() {

   Route::get('/admin', function() {

      return 'Welcome Admin';
      
   });

});

 

Now you can use your controller like below to give user permission and access.

public function __construct()
{
   $this->middleware('auth'); 
}


public function store(Request $request)
{
    if ($request->user()->can('create-tasks')) {
        //Code goes here
    }
}

public function destroy(Request $request, $id)
{   
    if ($request->user()->can('delete-tasks')) {
      //Code goes here
    }

}

 

Read also : Understanding Constructor and Method Dependency Injection in Laravel

 

Now only those user can access this route whose role is developer. Hope you will understand total procedure. Hope it will help you.

 

Laravel News Links

The Best Bug Repellents

https://cdn.thewirecutter.com/wp-content/uploads/2019/03/bug-repellent-lowres-9664-630×420.jpg

The Best Bug Repellents

Everyone should avoid bug bites. For a bug repellent that’s safe and effective—and that won’t stink or leave a puddle of oil on your skin—skip the DEET and get a picaridin formula, like Sawyer Products Premium Insect Repellent with 20 percent picaridin. It’s the best bottle of bug spray we found after testing 17 repellents and talking to everyone—from the EPA to the American Mosquito Control Association. One fact to establish up front: There’s no evidence that mosquitoes can transmit the coronavirus—but the diseases that biting insects do carry ain’t no picnic either.

Wirecutter: Reviews for the Real World

Snake Eyes’ First Trailer Gives a G.I. Joe Legend a New Beginning

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/ec1af9416e1223be47bac498723dc5b8.jpg

Henry Golding as Snake Eyes in Snake Eyes: G.I. Joe Origins.
Photo: Paramount

Trailer FrenzyA special place to find the newest trailers for movies and TV shows you’re craving.

When you think of Snake Eyes you think of the mask, the swords, the unstoppable ferocity. But how did the popular G.I. Joe character become that guy we’ve seen in comics, cartoons, and toy aisles for decades? We’re about to find out, in a whole new way. The first trailer for Snake Eyes: G.I. Joe Origins is finally here.

The film stars Henry Golding as the titular character, seen here years before he meets up with the Joe crew. Directed by Robert Schwentke, Snake Eyes follows the character as he becomes indoctrinated into the Arashikage clan, learning the ways of the ninja alongside Storm Shadow (Andrew Koji), the group’s heir apparent, and eventually popular Joe characters like The Baroness (Úrsula Corberó), and Scarlett (Samara Weaving) show up too. But this is the Snake Eyes show and, in the first trailer, you get just a taste of what the film has in store.

The film is meant to kick off a whole new G.I. Joe franchise and if you’re curious to know more, check back soon—io9 spoke to Henry Golding all about it. Snake Eyes: G.I. Joe Origins hits theaters on July 23.


For more, make sure you’re following us on our Instagram @io9dotcom.

G/O Media may get a commission

Gizmodo

They really are the enemy of the poeple

https://gunfreezone.net/wp-content/uploads/2016/01/cropped-gfz-ico.png

Tell me why the AP was in a building that Hamas was using to store weapons.

Oh yeah, because the AP were acting as human shields for Hamas, assuming that Israel wouldn’t strike their offices while Hamas hid rockets in the basement.

Everything the Left criticizes people for is projection.

They accuse Israel of war crimes because they were using media offices to protect terrorist weapons caches.

Friday Funnies

https://gunfreezone.net/wp-content/uploads/2021/05/lock-downs-no-emotional-harm-the-shinning.jpg

 

 

 

 

 

 

Hitman’s Wife’s Bodyguard (Trailer)

https://theawesomer.com/photos/2021/05/hitmans_wifes_bodyguard_t.jpg

Hitman’s Wife’s Bodyguard (Trailer)

Link

Ryan Reynolds, Samuel L. Jackson, Salma Hayek, Antonio Banderas, and Morgan Freeman star in this action-comedy about a bodyguard who attempts to get out of the business and gets pulled back in to protect the wife of an unhinged killer. It looks like just the kind of madcap Summer romp we could use. In theaters 6.16.2021.

The Awesomer

Mike Driscoll: Python 101: 2nd Edition is FREE for PyCon 2021!

https://www.blog.pythonlibrary.org/wp-content/uploads/2020/02/py101_kick-300×179.jpg

I am making Python 101: 2nd Edition free during PyCon 2021. This sale will end, Monday, May 17th, 2021. You can get the book free using the following links:

If you like the eBook and you’d like to get a paperback version, you can get it on Amazon.

Python 101 2nd Ed Kickstarter

The second edition of Python 101 is completely rewritten from the ground up. In this book, you will learn the Python programming language and lots more.

This book is split up into four sections:

  1. The Python Language
  2. Intermediate Topics
  3. Creating Sample Applications
  4. Distributing Your Code

The post Python 101: 2nd Edition is FREE for PyCon 2021! appeared first on Mouse Vs Python.

Planet Python

Holosun – How to Zero Your New Optic

https://www.ammoland.com/wp-content/uploads/2021/05/Holosun-Red-dot-500×334.jpg

Make Range Time Rounds Count with Holosun
Make Range Time Rounds Count with Holosun

U.S.A.-(AmmoLand.com)- One of the best things about some of the optics advancements in recent years has been the ability to incorporate them into all sorts of firearms, including pistols. This proves extremely beneficial for acquiring a target with as little effort as possible and takes the guesswork out of aiming. For a new and inexperienced marksman, this gives immediate results with little effort; that is, if it’s dialed in correctly.

Holosun offers a broad range of reflex sights that will work on properly equipped pistols. The 407, 507, 508 and 509 series come with all sorts of options. Mounting interface, reticle choice and color are the most obvious choices that need to be made. While these optics series are going to be different sizes, they are adjusted in remarkably similar ways.

When first using a reflex optic – let’s use the 508 series, for example – check to see if there are any specific items or tools necessary for adjustments. While the 508 series need a small flathead screwdriver, other brands may require custom tools and measurement systems. This is one significant benefit and testament to the consistency of Holosun products.

The Process:

Here’s a few basics before we begin on the overall process. Every optic will have a north-south knob for adjustment and an east-west knob for adjustment. Depending on where you aim and the location of the impacts, any changes to point-of-impact would be made using these knobs. Holosun includes a small tool that can be used for making these adjustments. Every time the knob is twisted, there will be a small ‘click’ sound. Each click is equivalent to a 1 MOA adjustment which may be unnecessary to know depending on your method for finding zero.

#1: With standard sight co-witness:

With some pistol optic installation, the ability to use the standard sights may still be possible. One method of zeroing a reflex optic is to line the dot from the optic over – or directly on – where the point of aim would normally be on the standard sights. There is some personal preference when it comes to co-witnessing. The next step would be as easy as heading to the range. From there, if the projectile is traveling too far in any direction, move the reticle an appropriate amount using the built-in knobs.

#2: Without co-witness:

A bit more complicated, this method can also be used even when co-witnessing. While you can eyeball it and waste ammunition in the process, a 10-yard zero target makes the process move without a hitch.

Pistol zero targets will most likely have an MOA measurement built-in. They are reliable if a target is set up at the proper distance. With an optic mounted and the target set up at ten yards, fire a group of 5 shots. From the shot group, find the center and estimate the MOA adjustments necessary to reach the bullseye. Using the dials on the side of the optic, adjust accordingly. Remember, Holosun pistol optic adjustment values are 1 MOA per click, so a 3 MOA adjustment would be three clicks.

Final Steps:

Following any adjustments, it’s recommended to do the same target process 3-5 times. After each group, continue making slight adjustments if necessary. This will do several things.

  • First, it will work out the user’s cobwebs and any flinching that might have happened during the first group shots.
  • Second, it will allow the settling in of any irregularities with the pistol, such as lack of lubrication or magazine difficulties.
  • Third, it will also test the consistency of the ammunition itself. Ammunition is one of the largest uncontrollable variables when finding zero and the accuracy of any firearm.

Conclusion:

So, there you have it! Two methods of zeroing your pistol-mounted optic. Promptly, find some inexpensive ammunition and get out to the range. The only thing standing in the way of an accurate pistol is you… and ammunition prices…


About Holosun Technologies

Holosun Technologies, located in City of Industry, California, was established in 2013 by one of the industry’s most successful OEM manufacturers. Holosun is committed to creating innovative optic, laser/IR technologies that benefit a broad range of shooting, hunting, law enforcement, and military needs.

Over the course of the past decade, Holosun has been at the forefront of developing new sight technologies to fulfill a variety of shooting needs. Our product line includes innovations such as; 50,000 hr battery life, solar options, the ability to change reticles with the press of a button and IR/Laser units that utilize the most recent advancements in laser and LED technology. At Holosun, we pride ourselves on producing cutting-edge equipment with a competitive price that astounds the customer and the competition.

For more information, please visit WWW.HOLOSUN.COM

Holosun logo

The post Holosun – How to Zero Your New Optic appeared first on AmmoLand.com.

AmmoLand.com

Cheap, Highly Efficient New EV Motor Uses No Magnets

"An EV motor has been developed that uses no magnets, thus lessening the United States’ reliance on Chinese magnets (which make up 97% of the world’s supply)," writes Slashdot reader nickwinlund77, adding: "I wonder what the motor’s performance is like on high grade roads?" New Atlas reports: German company Mahle has just announced a new electric motor that sounds like it solves a lot of problems in a very tidy manner. The new Mahle design uses no magnets, instead using powered coils in its rotor. Unlike previous efforts, it transfers power to the spinning rotor using contactless induction — so there are basically no wear surfaces. This should make it extremely durable — not that electric motors have a reputation for needing much maintenance. The lack of expensive metals should make it cheaper to manufacture than typical permanent-magnet motors. Mahle says the ability to tune and change the parameters of the rotor’s magnetism instead of being stuck with what a permanent magnet offers has allowed its engineers to achieve efficiencies above 95 percent right through the range of operating speeds — "a level that has only been achieved by Formula E racing cars." It’s also particularly efficient at high speeds, so it could help squeeze a few extra miles out of a battery in normal use. The company says it’ll scale nicely from sizes relevant to compact cars up to commercial vehicles.
"Our magnet-free motor can certainly be described as a breakthrough, because it provides several advantages that have not yet been combined in a product of this type," says Dr. Martin Berger, Mahle’s VP of Corporate Research and Advanced Engineering. "As a result, we can offer our customers a product with outstanding efficiency at a comparatively low cost." Mass production is about two and a half years away, according to IEEE Spectrum, and Mahle has not yet nominated which auto manufacturers it’s dealing with, but test samples are already starting to circulate.


Read more of this story at Slashdot.

Slashdot

How to Insert at the First Position of a List in Python

https://blog.finxter.com/wp-content/uploads/2021/05/insert_list_first_pos.jpg

Problem Formulation: How to insert at the first position of a list in Python?

How to Insert at the First Position of a List in Python

Solution:

Use the list.insert(0, x) element to insert the element x at the first position 0 in the list. All elements j>0 will be moved by one index position to the right.

>>> lst = [5, 1, 3, 8, 7, 9, 2]
>>> lst.insert(0, 42)
>>> lst
[42, 5, 1, 3, 8, 7, 9, 2]

You create the list [5, 1, 3, 8, 7, 9, 2] and store it in the variable lst. Now, you insert the new element 42 to the first position in the list with index 0. Note that Python uses zero-based indexing so the first position has index 0. The resulting list has 8 elements instead of only 7. The new element 42 is at the head of the list. All remaining elements are shifted by one position to the right.

To dive deeper into the very important list.insert() method, I’d recommend you watch my full explainer video here:

Note that some people recommend to insert an element at the first position of a list like so:

>>> lst = [1, 2, 3]
>>> lst = ['new'] + lst
>>> lst
['new', 1, 2, 3]

While the output looks the same, this doesn’t actually solve the problem because the list concatenation operator list_1 + list_2 creates a new list with the elements of two existing lists. The original lists remain unchanged. Only by assigning it to the variable lst, you overwrite it. However, if another variable would point to the old list, this option based on list concatenation wouldn’t work because the old list remains unchanged.

>>> lst_1 = [1, 2, 3]
>>> lst_2 = lst_1
>>> lst_2 = ['new'] + lst_2

In this example, you create two lists lst_1 and lst_2 both referring to the same list object in memory. You try to insert the new element at the beginning of the list using the problematic method. And you obtain a clash—both lists refer to different objects in memory!

>>> lst_2
['new', 1, 2, 3]
>>> lst_1
[1, 2, 3]

Thus, the list.insert(0, 'new') method is superior to list concatenation to insert an element at a given position in the list.

>>> lst_1 = [1, 2, 3]
>>> lst_2 = lst_1
>>> lst_2.insert(0, 'new')
>>> lst_1
['new', 1, 2, 3]
>>> lst_2
['new', 1, 2, 3]

Both variables now refer to the same, changed list object.

The post How to Insert at the First Position of a List in Python first appeared on Finxter.Finxter